Updated 9/1/2015: My original method, keys(window)
gave unhelpful results in browsers other than Chrome. I've updated this post with a more reliable method.
2015年9月1日更新:我原来的方法, keys(window)
在Chrome以外的浏览器中没有帮助。 我已经用更可靠的方法更新了这篇文章。
JavaScript globals are considered bad. And as a contributor to the MooTools project, I've heard this on a daily basis for the better part of a decade. MooTools got knocked for extending natives but also for placing objects in the global space, like Browser
and $$
. I find the "global vars are terrible" philosophy a bit funny since even jQuery and JavaScript loaders use a global variable.
JavaScript全局变量被认为是不好的。 作为MooTools项目的贡献者,在过去十年的大部分时间里,我每天都听到这一消息。 MooTools因扩展本机而被淘汰,也因将对象(例如Browser
和$$
放置在全局空间中而被淘汰。 我发现“全局变量很糟糕”的哲学有点有趣,因为即使jQuery和JavaScript加载程序也使用全局变量。
Intentional globals aside, leaking global variables is bad practice and a result of sloppy coding. So how can we see what properties are custom within the global namespace? It's easier than you think:
除了有意使用全局变量外,泄漏全局变量是一种不好的做法,也是草率编码的结果。 那么,如何查看全局命名空间中自定义的属性呢? 它比您想象的要容易:
// UPDATE: This method is too naive
// Returns an array of window property names
//keys(window);
// Inject an iframe and compare its `contentWindow` properties to the global window properties
(function() {
var iframe = document.createElement('iframe');
iframe.onload = function() {
var iframeKeys = Object.keys(iframe.contentWindow);
Object.keys(window).forEach(function(key) {
if(!(key in iframeKeys)) {
console.log(key);
}
});
};
iframe.src = 'about:blank';
document.body.appendChild(iframe);
})();
You will see some variables there that you know you didn't set, like window
, document
, top
, and location
, but the others will have been leaked (or intentional) globals set by custom JavaScript code!
您将在其中看到一些您尚未设置的变量,例如window
, document
, top
和location
,但是其他变量将被自定义JavaScript代码设置泄漏(或故意)全局变量!