这个问题在这里已有答案:
我在类构造函数中的另一个模块中定义的异步函数上调用.bind(this)
。
课程如下
class CannedItem {
constructor (config) {
...
this._fetch = config.fetch.bind(this)
...
}
...
}
功能就像
module.exports = [
{
...
fetch: async () => {
// Want to refer to 'this' bound to the CannedItem object here
}
}
]
但是,当调用该函数时,this
绑定到一个空对象。
令人困惑的Visual Studio Code调试器在调试器窗口中将对象的范围绑定为this
,请参阅附带的屏幕截图,但是在控制台中检查变量会将其列为未定义。这对我来说就像有一个bug。是这种情况还是我滥用.bind()
?
唯一看起来有点不寻常的是异步功能。我尝试用异步和.bind()
搜索问题,但没有骰子。
我正在运行NodeJs 8.11.1和最新的VSCode(1.30.2)
您无法重新绑定箭头函数,因为this
固定为词汇定义的this
。如果您计划使用bind()
或其任何亲属,您需要常规功能:
class CannedItem {
constructor(config) {
this.myname = "Mark"
this._fetch = config.fetch.bind(this)
}
}
let obj = {
fetch: async() => { // won't work
return this.myname
// Want to refer to 'this' bound to the CannedItem object here
}
}
let obj2 = {
async fetch() { // works
return this.myname
// Want to refer to 'this' bound to the CannedItem object here
}
}
// pass arrow function object
let c1 = new CannedItem(obj)
c1._fetch().then(console.log) // undefined
// pass regular function object
let c2 = new CannedItem(obj2)
c2._fetch().then(console.log) // Mark
作为奖励,如果您使用常规功能,您可能不需要bind()
。
this._fetch = config.fetch
如果从实例中调用它,它将起作用。