在 Javascript 中使用“this”将一个类的对象传递给另一个类
所以,我有 java、c#、python 和该范围内其他语言的背景,我正在尝试基本上用 Javascript 重新创建一些东西。
我想使用“this”将 A 类的对象传递给 B 类,以便可以在 B 类中访问 A 类的实例。
import B from .....
class A
{
constructor()
{
Obj = new B // Make object of class B
b(this) // Send instance of class A to class B
}
methodA() // Method to test
{
alert("Hello!")
}
}
class B
{
constructor(a) //receive class A here in class B
{
a.methodA // call method of the instance class A
}
}
将 A 传递给 B 时,无法访问 b 中的方法 A
最佳答案
由于您在 B
构造函数中使用该对象,因此需要将 this
作为参数传递给 new B
。任何地方都没有 b()
函数。
您在调用a.methodA()
时也忘记了括号。
class A {
constructor() {
let Obj = new B(this) // Make object of class B
}
methodA() // Method to test
{
alert("Hello!")
}
}
class B {
constructor(a) //receive class A here in class B
{
a.methodA() // call method of the instance class A
}
}
let a = new A;
关于javascript - 使用 'this' 将类的对象传递给另一个类(Javascript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57402200/