简体   繁体   中英

Passing data values between two classes in JavaScript

I guess it is quite regular issue, but for some reason I cannot find the answer on the net.

So I have a class A:

class A {
   const data = {...}
} 

And a class B in a separate js file.

class B {
   // how can I get const data here?
}  

You could use composition, and instantiate new instance of class A inside of constructor of class B .

class A {
  constructor() {
    this.data = { foo: "bar" };
  }
}

class B {    
  constructor() {
    this.instanceOfA = new A();
    console.log(this.instanceOfA.data);
  }
}

console.log(new B());

Here is data passed by function/event in two class:

   class A {
     constructor(name) {
       console.log(name)
     }
    }

    class B {    
      y(){
        return "ram"
      }
    }

    let resultFromB = (new B().y());
    new A(resultFromB)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM