Javascript全局变量存储在哪个对象中? [英] What object are Javascript global variables stored in?

查看:158
本文介绍了Javascript全局变量存储在哪个对象中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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



我感觉好像这是愚蠢的,我应该已经知道,但我似乎甚至不能找到在线回答。


解决方案

我想你会发现在大多数浏览器中, code> window 。



疯狂的心理调试尝试:你在jsFiddle中测试了这个吗?或者在Firebug中?如果是这样,你可能会看到 undefined ,因为在这种情况下代码是在一个框架中执行的;所以它有一个不同的窗口对象(我认为)代码实际上是包装的:



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

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



我不是专家,但从Chrome,Firefox,Safari和Opera中可以看出,这个答案看起来是准确的。为了验证,我创建了一个包含以下内容的HTML文件,并将其加载到每个浏览器中:

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

果然,每次都是东西。

Are global variables stored in specific object? For instance:

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

All three of these tests result in undefined, so is there an object that holds these variables?

I feel as though this is something stupid that I should already know, but I can't even seem to find the answer online.

解决方案

I think you'll find on most browsers, they are stored in window.

Far-fetched psychic debugging attempt: did you test this in jsFiddle? Or perhaps in Firebug? If so, you're probably seeing undefined for all three because in that case the code is executed in a frame; so it has a different window object (I think) the code is actually wrapped:

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

You can see from the above snippet from jsFiddle that test is not a global variable, which explains why it hasn't been attached to window.

I'm no expert, but this answer appears to be accurate from what I can tell in Chrome, Firefox, Safari, and Opera. To verify, I created an HTML file with the following content and loaded it in each browser:

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

Sure enough, "stuff" every time.

这篇关于Javascript全局变量存储在哪个对象中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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