javascript - 使用“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
解决方案
由于您在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;
推荐阅读
- android - 调试 React-Native 项目时出现 VS Code 错误
- sorting - 有效地对切片列表进行排序
- c - 在C中查找列表的基数
- php - PHP - 如何使用变量制作计数按钮?
- python - 如何在python dict中包含空日期时间
- python - 读取和处理多个大型数据文件的良好做法?
- docker - ROS 安装后 Dockerfile RUN 命令停止工作
- android - 使用 exoplayer 的 Android kotlin 应用程序崩溃而没有错误指示
- amazon-aurora - 无法连接到 Aurora MySQL 数据库
- windows - PowerShell:客户端无法连接到请求中指定的目标