-1

Considering the next piece of es2015 code

class MyClass{
    constructor () {
        this.title = 'Title';
    }

    update(title) {
        this.title = title;
    }
}

what is the best way to make sure that inside of update handler I'm referencing my object with this? Currently I have a problem that an external library is calling this update not as an object method call but just as a function call and therefore a reference to this is not correct. Previously I could write something like var that = this; and reference that directly in my handler. But what is the best pattern to accomplish the same idea with es2015 syntax?

Jeremy
  • 1
  • 85
  • 340
  • 366
Andrey
  • 5,906
  • 4
  • 24
  • 30
  • In the example that you posted, `this` is always referenced to the instance of `MyClass`... The library that you're using probably loses the reference, but, this is not clear from your example. please, post a detailed use case... – Hitmands Dec 05 '15 at 11:33
  • Yes, the library I use does lose this reference, you're right. It basically calls my `update` handler without any context. My question is basically how to avoid that and make a call to my specific object from my handler without using `this` – Andrey Dec 05 '15 at 11:37
  • To help you I need more information about your specific case, but, for the moment you should have a look at this article https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind – Hitmands Dec 05 '15 at 11:54
  • 1
    Have a look at the possible duplicate [can i use ES6 fat arrow in class methods?](http://stackoverflow.com/q/31362292/1048572) – Bergi Dec 05 '15 at 15:07
  • Please show us how you are calling the external library. – Bergi Dec 05 '15 at 15:08
  • I pass my update function as a callback to knockoutjs binding (which is not mine). This binding calls my function later – Andrey Dec 05 '15 at 22:28
  • @Andrey: Just pass a bound function (`myInstance.update.bind(myInstance)`) or arrow function (`title => myIntance.update(title)`) instead – Bergi Dec 16 '15 at 00:16

2 Answers2

0

Since the use case is not totally clear, I recommend having a quick look at .bind() - basically it lets you pass in a value of 'this'.

luanped
  • 3,178
  • 2
  • 26
  • 40
0

this in JavaScript is defined by how the function is called.

The only way you can force the issue is to use Function.prototype.bind.

Ben Aston
  • 53,718
  • 65
  • 205
  • 331