gpt4 book ai didi

javascript - this 在自执行函数中的范围

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:38:48 29 4
gpt4 key购买 nike

谁能说出为什么全局范围不适用于以下情况?为什么第 6 行打印 undefined ?外部的“this”不应该在内部的自执行函数中可用吗?

var myObj = {
test1 : 4,
func : function(){
console.log(this.test1); //prints 4
(function(){
console.log("From self-executing function : " + this.test1); //prints undefined
})();
}
};

myObj.func();

因为,在以下情况下,全局范围工作正常。在外部作用域中声明的 test1 在内部函数中完全可用。

var test1 = 10;
(function(){
console.log("From self-executing function : " + test1); //prints 10
})();

任何人都可以解释一下我在这里缺少理解的内容吗?

最佳答案

在内部函数中,this 引用全局对象(如果不是在严格模式下)。

您可以像这样修改代码以获得您期望的结果:

var myObj = {
test1 : 4,
func : function(){
console.log(this.test1);
var self = this;
(function(){
console.log("From self-executing function : " + self.test1);
})();
}
};

myObj.func();

关于javascript - this 在自执行函数中的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54280146/

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