Object JavaScript – Declaring Globals inside a ‘use strict’ block

10063_580983808600819_401360548_nAs you learned in Scope, Namespaces, ‘use strict’, it’s considered good practice to use a self-invoking function to wrap strict mode compliant code, often called the strict mode pragma.

(function(){ 
  "use strict"; 
    // Strict code here
}());

But how do you declare a global?

If you do the following, it will assume the window object in the browser and also create a global in Node.js and where you may not have a window object.


(function(globals){
"use strict";
globals.GLOB = {};
}(this));

If you know you will be in a browser, you can assume the window object, or pass in the global:


(function(){
"use strict";
window.GLOB = {};
}());


(function(win){
"use strict";
win.GLOB = {};
}(window));

References

How to declare global variables when using the strict mode pragma