【问题标题】:ES6 Difference between arrow function and method definition [duplicate]ES6箭头函数和方法定义之间的区别[重复]
【发布时间】:2016-10-19 19:34:37
【问题描述】:

next函数有什么区别

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

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

为什么在第一种情况下this === window

【问题讨论】:

  • 这就是区别。箭头函数不绑定this

标签: javascript ecmascript-6 arrow-functions


【解决方案1】:

因为箭头函数不创建自己的 this 上下文,所以 this 具有来自封闭上下文的原始值。

在您的情况下,封闭上下文是全局上下文,因此箭头函数中的thiswindow

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

另一方面,常规函数的上下文是动态的,当此类函数作为对象上的方法调用时,this 指向该方法所属的对象。

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

上述语法使用ES6 method shorthand。它在功能上等同于:

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

【讨论】:

  • 非常清楚,谢谢!
猜你喜欢
  • 2016-01-25
  • 1970-01-01
  • 2018-08-02
  • 2018-07-18
  • 2020-03-28
  • 2016-03-25
  • 1970-01-01
  • 1970-01-01
  • 2018-09-28
相关资源
最近更新 更多