问题描述
全局变量是否存储在特定的对象中?例如:
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 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全局变量存储在哪个对象中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!