2

Right now in my helper is using function()

updateCVId: function() {
    return this._id; //return the real id

}

It's working, but if I use ()=>

updateCVId:()=> {
    return this._id; //return undefined
}

then this._id is undefined.

The same is for the events:

'click .foo': function(evt, tmp) {
    console.log(this._id); //log the real id
}

and

'click .foo': (evt, tmp)=> {
    console.log(this._id); //log undefined
}

Can someone tell me if I use ()=> , how to get the data?

Thank you guys.

Altimir Antonov
  • 4,966
  • 4
  • 24
  • 26
  • In arrow functions, *this* is assigned as the *this* of the execution context in which the function is created. In a function declaration or expression, it's set by the call (or *bind*) so likely a different object. – RobG May 09 '16 at 06:14
  • Ok, then how to get the data in arrow function as I take it with this in the normal function? – Altimir Antonov May 09 '16 at 06:16
  • Use a function declaration or expression (the first example), see [*Do ES6 arrow functions always close over “this”?*](http://stackoverflow.com/questions/35813344/do-es6-arrow-functions-always-close-over-this). – RobG May 09 '16 at 06:19

1 Answers1

4

Arrow functions => are designed to automatically bind the context this from lexical scope. In your situation this is undefined, because it runs in 'strict mode'.

To solve your problem you can:

1) Use a regular function, as you did already:

var actions = {
   //...
   updateCVId: function() {
      return this._id; //return the real id
   }
   //...
};

2) Use an ES6 shorthand function notation:

var actions = {
   //...
   updateCVId() {
      return this._id; //return the real id
   }
   //...
};

The difference between function() {} and => is in the this context and how the invocation affects this.

In function() {} this is determined by the way function is invoked. If invoking it as a method on the object, this will be the object itself: actions.updateCVId().
I call it soft linked this.

In an arrow function case => this is automatically bound to this of the lexical scope where the function is defined. In your example it's an undefined, which is default case for 'strict mode'.
No matter how the arrow function is invoked later, it will have this as undefined.
I call it hard linked this.

You can find more details about this keyword in this article.

Dmitri Pavlutin
  • 18,122
  • 8
  • 37
  • 41