argon argon - 5 months ago 12
Node.js Question

JavaScript - how to identify or define THE "global" (super-global) for cross-platform use in strict mode

global reference



I'm looking for a way to check if the "global" (super-global, -like "window") exists -and if not, to create it as such.

I've seen this done in some code on GitHub a few weeks ago, but, now that I need it, I can't find it anywhere. I may have miss-looked, but it was very short and all intelligent like on 1 (short) line - without
if
, and without using
var
(or
let
) - in global scope --> in strict mode.

I've been searching for 2 hours trying to find this and all I can find is countless references to "global variables" - which in this case, clearly not a "variable" as the super-global "window" (or in NodeJS "global") is not mutable.

The solution I currently have is not that great, but it works, sort-of:

"use strict";

if ('undefined' == typeof global)
{
Object.defineProperty
(
window,'global',
{
writable:false,
configurable:false,
enumerable:false,
value:window
}
);
}


So, if you try something like:

global = 'bite me!';


Then the behavior is as expected, it throws:


Uncaught TypeError: Cannot assign to read only property 'global' of...


Which is good, -exactly as it should behave.




I'm not sure if this is the correct way to define it, because if I do something like:

console.log(global);


Then the console shows something like this:


Window {top: Window, ...


Which tells me that it is not identified as "global" but as "window"; -which is all fair and well being a "circular"; however, I'm sure there's a better way to do this.

Any input will be much appreciated, thanks

Answer

I never thought this would actually work; but it does!
In global scope, after use strict; you can simply do this:

this.Main = this;

Now you can simply call and define things on Main as you would with window -or- global; and these new properties will exist in the global scope as expected.

After you've made the changes you want to this object; simply call:

Object.freeze(this.Main);  // makes it immutable


If you want to do it all in one go (for no valid reason whatsoever) you can do this:

Object.freeze(this.Main=this);  // it actually works!