1

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?

francesca
  • 559
  • 3
  • 10
  • 19

1 Answers1

3

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 invoked 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 handler() {
    // `this` points to `obj` as its context, `this === obj`
  }
}
nem035
  • 34,790
  • 6
  • 87
  • 99