Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare global variables when using the strict mode pragma

Tags:

javascript

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?

like image 390
johnwilander Avatar asked Feb 22 '12 15:02

johnwilander


People also ask

How do you declare a variable in strict mode?

Declaring Strict Mode Strict mode is declared by adding "use strict"; to the beginning of a script or a function.

Is it possible to use undeclared variables in strict mode?

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.

How do you declare a global variable?

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.

How do you declare global variables in pho?

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.


2 Answers

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)); 
like image 61
Stepan Riha Avatar answered Sep 21 '22 05:09

Stepan Riha


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

like image 44
Adassko Avatar answered Sep 23 '22 05:09

Adassko