0

I'm having trouble figuring out when do I need to bind the instance to a function.

For example, say I'm using a service function that returns a Promise<void> and i dont want to use an anonymous function in my then-chain, i'd like to do something like this:

this.someService.somePromiseMethod().then(this.doSomething)`

the doSomething:

public doSomething(){
  this.a = 2
}

But this fails since it does not recognize the a of this (undefined)

While using : this.someService.somePromiseMethod().then(this.doSomething.bind(this) works

WHY? The call to the service is done within the instance, why do I still need to bind this instance to the function call?

Thanks in advance for any clarifications!

Kesem David
  • 2,135
  • 3
  • 27
  • 46
  • Here is the link to the MDN documentation, it's usually well written and with lots of examples https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this – Julio Bastida Aug 18 '17 at 14:53
  • Why? Because your function is not executing in the context of the object to which `this` refers, but a callback invoked by use of a promise. – James Aug 18 '17 at 15:35
  • @James I see, is there any way of achieving this behavior without adding the `.bind(this)` for every `then` call? – Kesem David Aug 18 '17 at 15:43
  • Perhaps you can define a second function in your class which is a bound copy of your first function (or define the first function as an anonymous function which is then bound to `this`). I don't use class-based JS much but something like `this.boundFunc = this.func.bind(this);`, and then use `this.boundFunc` as your callback. – James Aug 18 '17 at 16:21

0 Answers0