不能重新绑定箭头函数,因为
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
作为奖励,如果使用常规函数,则可能不需要
绑定()
.
this._fetch = config.fetch
如果您从实例调用它,它将工作。