Javascript:在JavaScript中是否有相当于lua的_G?
Javascript: Is there an equivalent of lua's _G in JavaScript?
在 lua 中,我可以执行以下操作:
_G.print("Hello world")
print("Hello world")
并且它会将相同的字符串打印到屏幕上。
有没有办法访问 javascript 中的全局对象?我是说喜欢
_G.console.log === console.log
true
这对我的用例非常有帮助(我想通过扫描全局对象的更改来防止我网站上的任何代码注入)
在浏览器中您可以使用 window
或 self
。在 Node 中你可以使用 global
。然而,这不是一般的标准化,而是 there is a proposal for standardizing 它。该提案还展示了一种与环境无关的方式来获取全局对象:
var getGlobal = function () {
// the only reliable means to get the global object is
// `Function('return this')()`
// However, this causes CSP violations in Chrome apps.
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');
};
在 lua 中,我可以执行以下操作:
_G.print("Hello world")
print("Hello world")
并且它会将相同的字符串打印到屏幕上。 有没有办法访问 javascript 中的全局对象?我是说喜欢
_G.console.log === console.log
true
这对我的用例非常有帮助(我想通过扫描全局对象的更改来防止我网站上的任何代码注入)
在浏览器中您可以使用 window
或 self
。在 Node 中你可以使用 global
。然而,这不是一般的标准化,而是 there is a proposal for standardizing 它。该提案还展示了一种与环境无关的方式来获取全局对象:
var getGlobal = function () { // the only reliable means to get the global object is // `Function('return this')()` // However, this causes CSP violations in Chrome apps. 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'); };