- 示例代码
方法1
var gloabl = typeof window !=="undefined"?
window : typeof process == "object" && typeof require == "function"&& typeof global =="object"?
global : this;
方法2
var global =function(){
if(typeof self!=="undefined") return self;
if(typeof window!=="undefined") return window;
if(typeof global!=="undefined") return global;
}();
2.方法解析
js的全局变量是一个虚拟概念,客户端浏览器的环境下,js 的全局变量默认为window,在nodeJS环境下,全局变量就是global,web Worker中的self也可以指向全局变量,浏览器下也可以。
在浏览器中,top,self,parent都可以指向父级的作用域;
访问子iframe中的需要调用contentWindow对象