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 }());
My question is how to declare global variables in this case? Three alternatives that I know of today:
Alternative 1:
var GLOB = {}; (function(){ "use strict"; }());
Alternative 2:
(function(){ "use strict"; window.GLOB = {}; }());
Alternative 3:
(function(win){ "use strict"; win.GLOB = {}; }(window));
Any preferences and motivations? Other options?
Declaring Strict Mode Strict mode is declared by adding "use strict"; to the beginning of a script or a function.
Variables must be declared before they can be assigned to. Without strict mode, assigning a value to an undeclared variable automatically creates a global variable with that name. This is one of the most common errors in JavaScript. Strict mode makes it impossible to accidentally create global variables.
The global Keyword Normally, when you create a variable inside a function, that variable is local, and can only be used inside that function. To create a global variable inside a function, you can use the global keyword.
Global variables refer to any variable that is defined outside of the function. Global variables can be accessed from any part of the script i.e. inside and outside of the function. So, a global variable can be declared just like other variable but it must be declared outside of function definition.
IMO alternative 3 is best. But it assumes that window
represents the global scope - which is true for the browser but not for other JS environments (command line, Node.js, etc.).
The following will work across the board:
(function(globals){ "use strict"; globals.GLOB = {}; }(this));
I know this is an old question but there's one not mentioned way of getting global context:
(function(globals){ "use strict"; globals.GLOB = {}; }( (1,eval)('this') ));
(1,eval)('this')
will evaluate this
from global context, so you can paste this wherever you like and you will always get global context
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With