ES6 Difference between arrow function and method d

2019-05-30 05:12发布

问题:

This question already has an answer here:

  • Are 'Arrow Functions' and 'Functions' equivalent / exchangeable? 3 answers

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?

回答1:

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 handler() {
    // `this` points to `obj` as its context, `this === obj`
  }
}