ES6 Difference between arrow function and method definition [duplicate]

瘦欲@ 提交于 2019-12-08 05:33:43

问题


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 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`
  }
}


来源:https://stackoverflow.com/questions/40140075/es6-difference-between-arrow-function-and-method-definition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!