代码之家  ›  专栏  ›  技术社区  ›  Brendan

在异步函数上调用“bind()”部分工作[重复]

  •  -1
  • Brendan  · 技术社区  · 7 年前

    这个问题已经有了答案:

    我打电话来 .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代码调试器将范围内的对象绑定为 在调试器窗口中,请参见附加的屏幕截图,但是检查控制台中的变量会将其列为未定义。在我看来,好像有一只虫子。是这样还是我误用了 .bind() ?

    唯一有点不寻常的是异步函数。我试图寻找异步和 B.() 但没有骰子。

    我正在运行nodejs 8.11.1和最新的vscode(1.30.2)

    Screenshot showing the discrepancy between debugger and output

    1 回复  |  直到 7 年前
        1
  •  1
  •   Mark    7 年前

    不能重新绑定箭头函数,因为 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
    

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