javascript-globalThis

全局属性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方法");
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值