gpt4 book ai didi

javascript - 因为它可以访问外部对象

转载 作者:行者123 更新时间:2023-11-30 17:05:29 24 4
gpt4 key购买 nike

我正在尝试执行一小段代码并查看。我得到以下结果。对每个结果给出解释。你们能告诉我它是否正确吗?

var myObject = {
foo: "bar",
func: function() {
var self = this;
console.log("outer func: this.foo = " + this.foo);
console.log("outer func: self.foo = " + self.foo);
(function() {
console.log("inner func: this.foo = " + this.foo);
console.log("inner func: self.foo = " + self.foo);
}());
}
};
myObject.func();


outer func: this.foo = bar ------------> since it has access to outside object
outer func: self.foo = bar ------------> since it has access to outside object
inner func: this.foo = undefined ------------> dont know why its undefined
inner func: self.foo = bar ------------> since it has access to variable self

最佳答案

它在内部函数中是未定义,因为它在自调用函数 中。在自调用函数中,this 的值成为 window 全局对象。因此,由于 window.foo 未定义,this.foo 也未定义,因为 this === window 在该内部函数中。

关于javascript - 因为它可以访问外部对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28118165/

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