在异步函数上调用`bind()`部分有效

时间:2019-01-11 22:51:02

标签: javascript node.js bind

我在类构造函数内部另一个模块中定义的异步函数上调用.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,请参见所附的屏幕截图,但是在控制台中检查变量会将其列出为未定义。在我看来,这似乎是一个错误。是这种情况还是我滥用.bind()

似乎唯一不寻常的是异步功能。我尝试用async和.bind()搜索问题,但没有骰子。

我正在运行NodeJs 8.11.1和最新的VSCode(1.30.2)

Screenshot showing the discrepancy between debugger and output

1 个答案:

答案 0 :(得分:1)

您无法重新绑定箭头功能,因为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
如果您从实例调用

,它将起作用。

相关问题