【问题标题】: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?
【问题讨论】:
标签:
javascript
ecmascript-6
arrow-functions
【解决方案1】:
因为箭头函数不创建自己的 this 上下文,所以 this 具有来自封闭上下文的原始值。
在您的情况下,封闭上下文是全局上下文,因此箭头函数中的this 是window。
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`
}
}