我有这个代码:
<script>
console.log( Object.keys( this ) );
</script>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
console.log( Object.keys( this ) );
</script>
在 Firefox 中,控制台记录如下:
[ "window", "document", "InstallTrigger", "console", "getInterface" ]
[ "window", "document", "InstallTrigger", "console", "getInterface", "location", "$", "jQuery" ]
现场演示: http://jsfiddle.net/eX8jQ/
请注意 jQuery 执行后 Object.keys(this)
是如何返回另外三个元素的。我明白为什么要添加 "$"
和 "jQuery"
,但为什么要添加 "location"
?
我还在 Chrome 和 IE10 中进行了测试。在两者中,仅添加了 "$"
和 "jQuery"
。
最佳答案
jQuery 1.9.1 在其内部初始化代码中包含以下内容:
var location = window.location;
在顶层上下文中,this
是 window
,因此您正在测试 Object.keys(window)
。显然,Firefox 神奇地处理了 window.location
属性——它不会出现在 keys
中,除非它被访问。所以上述赋值的一个副作用是导致它出现在那里。
这个局部变量不在 jQuery 1.11.1 或 jQuery 2.1.1 中,所以简单地加载 jQuery 不应该有这个副作用。
关于javascript - 为什么在我将 jQuery 添加到页面后 "location"属性最终出现在 Object.keys() 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14761987/