【问题标题】:Use .call when I instantiate a new class当我实例化一个新类时使用 .call
【发布时间】:2018-03-10 13:06:49
【问题描述】:

我尝试在我的 mainClass 中调用 classA 的函数。然后我尝试在classA中调用mainClass的函数。我尝试使用 .bind() 和 .call() 但它不起作用。它仅在我在函数上使用 .bind(this) 或 .call(this) 时才有效,但在我尝试实例化新类时无效。

index.js

let ClassA = require('./ClassA')

class mainClass {

    constructor() {
        this.doSomething()
    }

    doSomething() {
        let classA = new ClassA().call(this)
        classA.doSomething()
    }

    aFunction() {
        console.log('done')
    }

}

new mainClass()

classA.js

module.exports = class ClassA {

    constructor() {
    }

    doSomething() {
        console.log('doSomething')
        this.doSomething2()
    }

    doSomething2() {
        this.aFunction() // main Class
    }

}

TypeErrpr:this.doSomething2 不是函数

【问题讨论】:

  • 您想通过.call(this) 实现什么目标?如果你只是删除它,你的代码就可以工作......
  • 旁注:通常,从构造函数中调用实例方法是一种反模式。 个用例,但总的来说,最好避免使用。
  • 那我如何从 classA 调用 aFunction() 呢?

标签: javascript node.js ecmascript-5 ecma


【解决方案1】:

在评论中,您已经澄清了您要做什么(这也是问题中的代码评论):

那我怎样才能从 classA 调用 aFunction() 呢?

您可以通过让 ClassA 中的代码访问您的实例来做到这一点。您可以将它传递给可以将其保存为实例属性的构造函数,或者您可以将其传递给doSomething

这是一个将其传递给构造函数的示例:

class ClassA {

    constructor(obj) {           // ***
        this.obj = obj;          // ***
    }

    doSomething() {
        console.log('doSomething');
        this.doSomething2();
    }

    doSomething2() {
        this.obj.aFunction();    // ***
    }

}

class mainClass {

    constructor() {
        this.doSomething();
    }

    doSomething() {
        let classA = new ClassA(this);
        classA.doSomething();
    }

    aFunction() {
        console.log('done');
    }
}

new mainClass();

【讨论】:

    猜你喜欢
    • 2015-09-10
    • 1970-01-01
    • 2012-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-28
    • 1970-01-01
    相关资源
    最近更新 更多