ES6箭头功能和方法定义之间的差异 [英] ES6 Difference between arrow function and method definition
问题描述
下一个函数之间有什么区别
What is the difference between next functions
module.exports = utils.Backbone.View.extend({
handler: () => {
console.log(this);
}
});
和
module.exports = utils.Backbone.View.extend({
handler() {
console.log(this);
}
});
为什么在第一种情况下这个===窗口
?
Why in first case this === window
?
推荐答案
因为箭头函数不会创建自己的上下文,所以 this
具有封闭上下文中的原始值。
Because arrow functions do not create their own this context, so this
has the original value from the enclosing context.
在您的情况下,封闭上下文是全局上下文所以 this $ c箭头函数中的$ c>是
窗口
。
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`
}
}
以上语法使用 ES6方法的简写。它在功能上等同于:
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`
}
}
这篇关于ES6箭头功能和方法定义之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!