node.js - 如何在另一个类中使用类函数?

标签 node.js class

如何在另一个类中使用类实例,就像 C++ 中指向类实例函数的指针一样?

示例:

class A {
    constructor()
    { 
       this.block = [];
    }

    method()
    {
       return this.blocks.length;
    }
}

另一个类:

class B {
    constructor(instance)
    { 
       this.instance = instance;
    }

    method()
    {
        this.instance.method(); // here i'm getting cannot get length of undefined
    }
}

如果我想喜欢它,我会遇到调用它的问题

最佳答案

你可以试试这个。在这里,当创建 B 类的实例时,我给它一个 A 类的实例作为参数。然后在B内部我们可以调用A实例的方法,并访问它的属性。

此外,正如 @ViaTech 所发布的,您可以使用静态方法来访问它们,而无需初始化类的对象。这就是静态方法。请参阅Static Methods

class B {
    constructor(instance)
    {
        this.instance = instance;
    }

    method()
    {
        this.instance.method();
    }
}
class A {
    constructor()
    {

    }

    method()
    {
    console.log("A's method");
    }
}

var a = new A();
var b = new B(a);
b.method(); // A's method

关于node.js - 如何在另一个类中使用类函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55801421/

相关文章:

node.js - 无法在 Google Cloud Function 中加载 node_modules(index.js,不在项目根目录上)

node.js - 我正在 Node.js 上开发 Express 4 应用程序。我在渲染新 View 时遇到问题

c# - 将 C# 类转换为 JavaScript

python - 如何在 tkinter 中单击按钮后更新 Canvas 上的文本

c# - 从类调用寻呼

javascript - 诗乃类型错误 : Attempted to wrap <method> which is already wrapped when running multiple scripts

node.js - 在这种情况下, "npm start"的等效 Node 命令是什么?

swift - 使用类中的函数初始化变量

mysql - 如何转义撇号以匹配 Node.js/Discord.js 中 MySQL 数据库的数据?

具有多个分类的 div 框的 jQuery Cookie