全局属性globalThis包含全局的this值,类似于全局对象(Global object);
function canMakeHTTPRequest() {
return typeof globalThis.XMLHttpRequest === 'function'
}
在以前,从不同的Javascript环境获取全局对象需要不同的语句,在web中可以使用window,self 或者frames获取全局对象,但是在web workers 中 只有self可以, 在nodejs中则是须用global,
在松散模式下。可以在函数中返回this来获取全局对象,但是在严格模式下this会返回undefined
但是可以 使用
Function("return this")();
globalThis提供了一个标准的方式来获取不同环境下的全局this对象,不必担心运行环境。
在es6-shim使用了如下方式
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")
}
var globals = getGlobal();
if (typeof globals.setTiomeout !== "function") {
alert("此环境中没有setTimeout方法")
}
有了globaleThis之后 只需要
if(typeof gloableThis.setTimeout !== "funciton") {
alert("此环境中没有setTimeout方法");
}