Javascript全局变量存储在哪个对象中

What object are Javascript global variables stored in?

本文关键字:对象 全局变量 存储 Javascript      更新时间:2023-11-27

全局变量是否存储在特定对象中?例如:

var test="stuff";
console.log(window.test);
console.log(document.test);
console.log(this.test);

这三个测试的结果都是undefined,那么是否有一个对象包含这些变量?

我觉得这是一件愚蠢的事情,我应该已经知道了,但我似乎甚至无法在网上找到答案。

这是一个迟来的但技术性的答案。

你问

全局变量是否存储在特定对象中?

答案是肯定的;它们被存储在一个官方称为的全局对象中。该对象在官方ECMAScript 5规范的第15.1节中进行了描述。

全局对象不需要有名称;但您可以简单地使用其名称来引用其属性,例如StringisNaNDate。您的JavaScript主机环境将在全局对象中放置ECMAScript规范所需的属性之外的其他属性,例如alertconsole。在浏览器中,我可以编写脚本

alert("Hello world");

因为CCD_ 7是全局对象的属性。

请注意,信不信由你,根本不必有访问这个全局对象的方法。然而,最酷的是,许多主机环境会在全局对象中放置一个属性,其值是对全局对象本身的引用。在大多数web浏览器中,此属性称为window。所以我们可以写:

alert("Hello");
window.alert("Hello");
window.window.alert("Hello");
window.window.window.window.window.alert("Hello");

你也可以说:

var x = 5;
alert(this.x);

并得到CCD_ 9的警报。

我想你会在大多数浏览器上发现,它们存储在window中。

牵强的心理调试尝试:你在jsFiddle中测试过吗?或者可能在萤火虫?如果是这样的话,您可能会看到这三种情况的undefined,因为在这种情况下代码是在一个帧中执行的;所以它有一个不同的window对象(我认为)代码实际上是被包装的:

window.addEvent('load', function() {
  var test="stuff";
  console.log(window.test);
  console.log(document.test);
  console.log(this.test);
});

您可以从jsFiddle的上面片段中看到,test而不是全局变量,这解释了为什么它没有附加到window

我不是专家,但根据我在Chrome、Firefox、Safari和Opera中的判断,这个答案似乎是准确的。为了验证,我创建了一个包含以下内容的HTML文件,并将其加载到每个浏览器中:

<script type="text/javascript">
  var test = "stuff";
  alert(window.test);
</script>

果不其然,每次都是"东西"。

"true"全局变量没有"var"关键字。试试这个:

test="stuff";
console.log(window.test);
console.log(document.test);
console.log(this.test);

有了这个,所有作用域都会看到它。带有var关键字的变量是它们所声明的作用域的本地变量。

只有像Dan所说的那样在窗口范围中声明变量,使其对通常使用window作为全局范围的浏览器是全局的,变量才会是"global-to-window"(窗口对象的属性)。

全局变量存储在全局window变量中。如果你只是在任何东西之外声明它(比如函数),下面的代码就会起作用:

var test="stuff";
console.log(window.test);

类似的证明是window.location.hreflocation.href 相同

然而,问题可能在于变量的声明位置。例如,如果您在函数中声明了这个变量,它将只存在于函数中,而不全局存在:

function foo(){
    //declaring inside function
    var test="stuff";
    //undefined, since the variable exists in the function only
    console.log(window.test);  
    //undefined, document refers to the document
    //which is the top DOM object, not the global window
    console.log(document.test); 
    //depends on what "this" refers to, especially 
    //when using call() or apply() to call the function
    //For normal function calls, usually it points to window as well
    console.log(this.test);  
    //none of the above refer to "test" that contains "stuff"
    //because you are looking in the wrong place   
}