问题描述
var foo = 'bar';
console.log(window.foo); // bar
好像变量被分配为 this
的属性,但是在匿名函数中, this
引用父作用域,但未将变量分配给父作用域.
Seems like variables get assigned as properties to this
, but inside anonymous functions, this
refers to the parent scope, but doesn't assign variables to the parent scope.
function() {
var foo = 'bar';
}();
window.foo; // undefined
在非全局范围内将变量分配给哪个对象?
推荐答案
引用 http://perfectionkills.com/understanding-delete/#execution_context :
当控件进入全局代码的执行上下文时,全局对象
用作变量对象
.这就是为什么变量或全局声明的函数成为 Global对象
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
但是,这些 Variable Object
无法访问.唯一的非内部对象是全局对象,即 window
或 this
(在全局上下文中).
Yet, these Variable Object
s are not accessible. The only non-internal one is the global object, window
or this
(in global context).
规范中的相关部分是#10:可执行代码和执行上下文.
这篇关于为什么将全局范围内的变量分配给窗口对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!