为什么将全局范围内的变量分配给窗口对象? [英] Why do variables in the global scope get assigned to the window object?

查看:36
本文介绍了为什么将全局范围内的变量分配给窗口对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 :

每个执行上下文都有一个所谓的 Variable Object 用它.与执行上下文类似,变量对象是一个抽象实体,一种描述变量实例化的机制.现在,有趣的是,在实际上,添加了源文本作为此Variable对象的属性.

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.

当控件进入全局代码的执行上下文时,全局对象用作变量对象.这就是为什么变量或全局声明的函数成为 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 Objects are not accessible. The only non-internal one is the global object, window or this (in global context).

规范中的相关部分是#10:可执行代码和执行上下文.

这篇关于为什么将全局范围内的变量分配给窗口对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆