2017-10-06 92 views
3

Lua中,我能做到以下幾點:Javascript:在JavaScript中是否有相當於lua的_G?

_G.print("Hello world") 
print("Hello world") 

它都將打印相同的字符串到屏幕上。 有沒有辦法在javascript中訪問全局對象?我的意思是像

_G.console.log === console.log 
true 

這將是我的使用情況下,真正有用的(我想阻止我的網站上的任何代碼注入掃描更改全局對象)

+0

我認爲這是'window'你找......對於如'window.console.log' –

+0

它不工作在node.js(我preffer一個通用的解決方案) – Rph

回答

3

在瀏覽器中,您可以使用windowself 。在節點中,您可以使用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'); 
};