Javascript: Is there an equivalent of lua's _G in JavaScript?

Viewed 302

In lua, I can do the following:

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

And it will both print the same string to the screen. Is there a way to access the global object in javascript? I mean like

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

It will be really helpful in my use case (I want to prevent any code injection on my website by scanning the global object for changes)

1 Answers

In browsers you can use window or self. In Node you can use global. However this is not standardized in general, but there is a proposal for standardizing it. The proposal also shows an environment agnostic way to get the global object:

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');
};
Related