gpt4 book ai didi

javascript - 为什么全局范围内的变量被分配给窗口对象?

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:36:19 24 4
gpt4 key购买 nike

var foo = 'bar';
console.log(window.foo); // bar

似乎变量作为属性分配给 this,但在匿名函数中,this 引用父作用域,但不会将变量分配给父作用域。

function() {
var foo = 'bar';
}();

window.foo; // undefined

变量在非全局范围内分配给什么对象?

最佳答案

引用http://perfectionkills.com/understanding-delete/#execution_context :

Every execution context has a so-called Variable Object associated with it. Similarly to execution context, Variable object is an abstract entity, a mechanism to describe variable instantiation. Now, the interesing part is that variables and functions declared in a source text are actually added as properties of this Variable object.

When control enters execution context for Global code, a Global object is used as a Variable object. This is precisely why variables or functions declared globally become properties of a Global object

然而,这些可变对象是不可访问的。唯一的非内部对象是全局对象、windowthis(在全局上下文中)。

规范中的相关部分是#10: Executable Code and Execution Contexts .

关于javascript - 为什么全局范围内的变量被分配给窗口对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10901284/

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