前端JavaScript全局对象获取通用方法

在学习ES6语法的过程中,看到了JavaScript获取全局对象的通用方法,记录上,以防日后用的上。


方法一

1
2
3
4
5
6
7
(typeof window !== 'undefined'
? window
: (typeof process === 'object' &&
typeof require === 'function' &&
typeof global === 'object')
? global
: this);

方法二

1
2
3
4
5
6
var getGlobal = function () {
if (typeof self !== 'undefined') { return self; }
if (typeof window !== 'undefined') { return window; }
if (typeof global !== 'undefined') { return global; }
throw new Error('unable to locate global object');
};

坚持学习。。。。。。


前端JavaScript全局对象获取通用方法
http://pygo2.top/articles/19661/
作者
mingliang.gao
发布于
2023年4月8日
许可协议