How to get the global object in JavaScript? -


I want to check in a script if another module is already full.

  If (ModuleName) {// extends this module}  

but if ModuleName is not present, then Throw s.

If I knew that global object I could use it

  if (window.ModuleName) {// expand this module }  

But since I want to work with both modules both browsers and nodes , rhino , etc., Code> window .

As I think, it does not work in ES 5 "Use Strict" ;

  var MyGLOBAL = (function () {this return;} ()); // MyGlobal becomes zero  

This will also fail with a thrown exception

  var MyGLOBAL = window || Global  

It looks like I have been left with

  try {// expanded module name} (ignore) {}  < / <> <> 

>

OK, you can type typeof , And if the identifier is not present in any location, then it not error , it is currently "undefined" :

  will come back if (typeof ModuleName! = 'Undefined') {// ...}  

Also remember that on the global code this Science, refers to the global object, which means that if your if statement on the global context, you can simply this.ModuleName .

About (function () {this;};} ()); The technique, you are right, the this value will be just undefined on the strict mode.

  Miscellaneous global = function ('return it') ();     

Function The constructor created with the constructor does not inherit the caller's strictness, only when he / she accepts

< P> This method is compatible with any ES3 implementation.

  • For example indirect eval calls ,

      "Strict Use the"; Var get = eval; Var global = get ("this");   

    The above will work because in ES5, use eval as both indirect calls, variable environment and language Related Details

    View Details on Step 1

    But keep in mind that the final solution will not work on ES3 implementation, because the variables and lexical environments of caller on eval ES3 will be used as an environment for evil codes.

    And finally, you can find out if hard mode is supported:

      var isStrictSupported = (function () {"strict use"; return ! this;}) ();  

Comments