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 stri
Benefit of alt 2 and 3 is that they keep all of the code inside the "container function." One line of code outside of the function is easy to miss when reading the code.
Also:
Andrea Giammarchi has a nice technique for doing this, that works across browsers. Define a function in your self-invoking function called globalEval like so:
(function () {
"use strict";
function globalEval(data) {
data = data.replace(/^\s*|\s*$/g, "");
if (data) {
var head = document.getElementsByTagName("head")[0] || document.documentElement,
script = document.createElement("script");
script.type = "text/javascript";
script.text = data;
head.appendChild(script);
head.removeChild(script);
}
}
// use globalEval to stick variables into the global scope
globalEval("var myGlobal = 1;");
// myGlobal === 1
)();
// myGlobal === 1
Or define the globalEval function outside of the self-invoking code if you want to use it in other scopes.
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));
Method 1 would fail if it's pasted in another function.
Using method 3, it is easier to export your methods to another namespace. Simply replacing window
with, say, frames[0]
or document
is enough to attach all methods to a custom namespace.
I recommend method 3, for the last reason.
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