【发布时间】: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