Object内部箭头函数的值 [英] Value of this inside arrow function inside an Object
问题描述
我以为我理解这个
和箭头函数之间的关系,但是下面的代码片段让我质疑我的理解。
I thought I understood the relationship between this
and arrow functions but the following snippet is making me question my understanding.
let person = {
name: 'Jim',
sayName: () => {
console.log(this.name);
}
};
person.sayName();
我知道箭头函数捕获这个
封闭上下文的值。我原以为这个
将是对象,而是 Window
。
I understand that arrow functions capture the this
value of the enclosing context. I was expecting this
would be the object but instead it is Window
.
有人可以帮我理解为什么会这样吗?
Can someone help me understand why this is the case?
推荐答案
您对箭头功能的理解大多是正确的:箭头函数有一个词汇 this
,它在箭头函数中的值由周围的范围决定。
Your understanding of arrow functions is mostly correct: Arrow functions have a lexical this
and its value within the arrow function is determined by the surrounding scope.
你可能假设此
在 person
对象文字中获得不同的值。 事实并非如此。
You probably assume that this
gets a different value within the person
object literal. This is not the case.
因此,让我们看看这个在您的(全局)范围内引用的内容:
So let's see what this
refers to in your (global) scope:
console.log(this === window); // true
let person = {
name: 'Jim',
test: console.log(this === window), // true
sayName: () => {
console.log(this === window); // true
}
};
person.sayName();
As你可以看到,当创建分配给 sayName
的箭头功能时,这个
指的是窗口
对象。
As you can see, when the arrow function assigned to sayName
is created, this
refers to the window
object.
这篇关于Object内部箭头函数的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!