全局变量在编程语言中一向被认为是一种不好的编程方法. 但现实情况是, 很多著名的项目都在大量的使用着全局变量, 比如, MooTools 就将大量的对象放到全局空间, 像 Browser 对象和 $$ 等. 而最著名的 jQuery 也是用的全局变量. 所以,"全局变量不好" 这个理论实际上处于一种很可笑的状态中.
而将全局变量暴露在外, 让用户任意修改 (除非是特意设计的), 更是一种不好的编程习惯, 这将对导致程序很难维护. 那么, 我们如何知道现有的全局变量空间里有哪些全局变量呢? 其实方法很简单:
- // UPDATE: This method is too naive
- // Returns an array of Windows property names
- //keys(Windows);
- // Inject an iframe and compare its `contentWindow` properties to the global Windows properties
- (function() {
- var iframe = document.createElement('iframe');
- iframe.onload = function() {
- var iframeKeys = Object.keys(iframe.contentWindow);
- Object.keys(Windows).forEach(function(key) {
- if(!(key in iframeKeys)) {
- console.log(key);
- }
- });
- };
- iframe.src = 'about:blank';
- document.body.appendChild(iframe);
- })();
用上面的代码我们可以做一下测试, 你可以直接按功能键 F12 来打开 console, 输入上面的代码, 观看输出结果. 你会发现, 有些对象, 比如 Windows, document, top, 和 location 都是 JavaScript 内置的, 而很多其它的对象, 都是第三方 JavaScript 代码产生的.
来源: http://www.webhek.com/post/get-global-variables-with-javascript.html