Altimir Antonov Altimir Antonov - 7 months ago 12
Javascript Question

MeteorJS - Differences between function() and () =>

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.

Answer

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.