As 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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function(){ | |
"use strict"; | |
window.GLOB = {}; | |
}()); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function(win){ | |
"use strict"; | |
win.GLOB = {}; | |
}(window)); |
References
How to declare global variables when using the strict mode pragma