ES6 箭头函数和方法定义的区别
ES6 Difference between arrow function and method definition
下一个函数有什么区别
module.exports = utils.Backbone.View.extend({
handler: () => {
console.log(this);
}
});
和
module.exports = utils.Backbone.View.extend({
handler() {
console.log(this);
}
});
为什么是第一种情况this === window
?
因为箭头函数不创建自己的 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`
}
}
下一个函数有什么区别
module.exports = utils.Backbone.View.extend({
handler: () => {
console.log(this);
}
});
和
module.exports = utils.Backbone.View.extend({
handler() {
console.log(this);
}
});
为什么是第一种情况this === window
?
因为箭头函数不创建自己的 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`
}
}