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

Bre*_*dan 2 javascript bind node.js

我正在调用.bind(this)类构造函数内的另一个模块中定义的异步函数。

班级如下

class CannedItem {
  constructor (config) {
    ...
    this._fetch = config.fetch.bind(this)
    ...
  }
  ...
}
Run Code Online (Sandbox Code Playgroud)

该功能类似于

module.exports = [
   {
      ...
      fetch: async () => {
        // Want to refer to 'this' bound to the CannedItem object here
      }
   }
]
Run Code Online (Sandbox Code Playgroud)

但是,当调用该函数时,this会绑定到一个空对象。

令人困惑的是,Visual Studio Code 调试器将对象限制this在调试器窗口中的范围内,请参阅随附的屏幕截图,但是检查控制台中的变量将其列为未定义。在我看来,这似乎有一个错误。是这种情况还是我滥用了.bind()?

唯一看起来有点不寻常的是 async 函数。我尝试寻找异步问题,.bind()但没有找到骰子。

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

显示调试器和输出之间差异的屏幕截图

Mar*_*yer 5

您无法重新绑定箭头函数,因为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
Run Code Online (Sandbox Code Playgroud)

作为奖励,如果您使用常规函数,则可能不需要bind().

 this._fetch = config.fetch
Run Code Online (Sandbox Code Playgroud)

如果您从实例调用它,它将起作用。