francesca francesca - 1 month ago 5
Javascript Question

ES6 Difference between arrow function and method definition

What is the difference between next functions

module.exports = utils.Backbone.View.extend({
handler: () => {
console.log(this);
}
});


and

module.exports = utils.Backbone.View.extend({
handler() {
console.log(this);
}
});


Why in first case
this === window
?

Answer

Because arrow functions do not create their own this context, so this has the original value from the enclosing context.

In your case, the enclosing context is the global context so this in the arrow function is window.

const obj = {
  handler: () => {
    // `this` points to the context outside of this function, 
    // which is the global context so `this === window`
  }
}

On the other hand, context for regular functions is dynamic and when such function is defined as a method on an object, this points to the method's owning object.

const obj = {
  handler() {
    // `this` points to `obj` as its context, `this === obj`
  }
}

The above syntax uses ES6 method shorthand. It is functionally equivalent to:

const obj = {
  handler: function() {
    // `this` points to `obj` as its context, `this === obj`
  }
}