脚本nodeJS出现此错误
问题描述:
我在学习NodeJS,并且遇到很大问题。脚本nodeJS出现此错误
使用ES6和执行与node --harmony
在我的构造this
告诉我它Magic {}
而bar()
它从我的功能。
我到处寻找,但我没有找到如何解决它。
#!/usr/local/bin/node --harmony
class Test {
constructor() {
var tab = []
tab.push(this.bar)
console.log(this) // Magic {}
tab[0]("hello")
// this.bar("world")
}
foo(str) {
return str
}
bar(str) {
console.log(this.foo(str)) // TypeError: this.foo is not a function
console.log(this) // [ [Function: bar] ]
}
}
new Test()
答
当你做tab.push(this.bar)
时,它会丢失当前的上下文。你需要a)绑定它:tab.push(this.bar.bind(this))
或者b)当调用时传递上下文:tab[0].call(this, "hello")
。
答
您必须在构造函数中绑定this
。
this.foo = this.foo.bind(this);
在构造函数中