gpt4 book ai didi

javascript - 嵌套对象文字中 'this' 的词法上下文

转载 作者:行者123 更新时间:2023-11-30 19:18:13 24 4
gpt4 key购买 nike

我问是因为我读过关于这个问题的类似(但不相同)的问题。

据我所知,我明白为什么这段代码有效:

let myObj = {
name: 'inner text',
myFunction: () => {
console.log("before text " + this.name + " after text");
}
}
myObj.myFunction();

原因:创建箭头函数的上下文(myObj)属于全局作用域(即window undefined 取决于严格模式等)。

我明白了。但是在嵌套对象字面量的情况下,外部对象字面量不应该是箭头函数的继承上下文,如下例所示吗?

let outer = {
name: 'outer',
obj: {
name: 'inner',
myFunction: () => {
console.log("before text " + this.name + " after text");
}
}
}
outer.obj.myFunction();

我希望 this 引用 outer 的上下文,它是嵌套 obj 的对象文字。
事实并非如此,这也是我没有正确理解这个继承的词法范围的原因。

有人能解释一下为什么会这样吗?

最佳答案

But in the case of nested object literals, shouldn't be the outer object literal the inherited context for the arrow function like following example?

没有。

箭头函数复制thiscurrent值;

var object = {
a: this,
b: {
a: this,
b: {
a: this
}
}
}

无论嵌套多少层,this 的值都不会改变。

由于对象字面量的每一层都出现在同一个函数中,它们都得到相同的this值。

关于javascript - 嵌套对象文字中 'this' 的词法上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57769860/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com