Search code examples
javascriptnode.jsbind

Calling `bind()` on an async function partially works


I'm calling .bind(this) on an async function defined in another module inside of a class constructor.

The class is as below

class CannedItem {
  constructor (config) {
    ...
    this._fetch = config.fetch.bind(this)
    ...
  }
  ...
}

The function is something like

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

However when the function is called, this is bound to an empty object.

Confusingly Visual Studio Code debugger has the object in scope bound as this in the debugger window, see attached screenshot, however inspecting the variable in the console lists it as undefined. This looks to me like there is a bug. Is this the case or am I misusing .bind()?

The only thing that seems a little unusual is the async function. I tried searching for issues with async and .bind() but no dice.

I am running NodeJs 8.11.1 and the latest VSCode (1.30.2)

Screenshot showing the discrepancy between debugger and output


Solution

  • You can't rebind arrow functions because this is fixed to the lexically defined this. You need a regular function if you plan on using bind() or any of its relatives:

    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

    As a bonus, if you use a regular function, you might not need bind().

     this._fetch = config.fetch
    

    will work if you call it from the instance.