简体   繁体   English

在JavaScript中的两个类之间传递数据值

[英]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: 所以我有A班:

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

And a class B in a separate js file. B类位于单独的js文件中。

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 . 您可以使用组合,并在类B的构造函数中实例化类A新实例。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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