使用JavaScript获取全局变量

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!

您将在其中看到一些您尚未设置的变量,例如windowdocumenttoplocation ,但是其他变量将被自定义JavaScript代码设置泄漏(或故意)全局变量!

翻译自: https://davidwalsh.name/global-variables-javascript

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值