1

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

Gama11
  • 31,714
  • 9
  • 78
  • 100
Brendan
  • 18,771
  • 17
  • 83
  • 114
  • The question was actually about use of async, not about binding of arrow function, so reference to duplicate is not useful. The question https://stackoverflow.com/questions/53313507/async-function-with-the-class-in-javascript Is more relevant – Michael Freidgeim Mar 10 '20 at 08:34

1 Answers1

4

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.

Mark
  • 90,562
  • 7
  • 108
  • 148
  • So the fact the debugger shows the value bound to `CannedItem` as I would expect is a red-herring? It basically shouldn't show that? – Brendan Jan 11 '19 at 23:04
  • In your debugger code it looks like `fetch` is directly on the object where the lexical `this` is the correct value. – Mark Jan 11 '19 at 23:07