首页 > 解决方案 > 使用“this”将一个类的对象传递给另一个类(Javascript)

问题描述

将使用“this”的类的对象传递给Javascript中的另一个类

所以,我来自 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

标签: javascript

解决方案


由于您在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;


推荐阅读