Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Wrapping entire script in a function call

Tags:

javascript

I've came across a few times with this phenomena in JavaScript, where an entire script is wrapped in a function call, like this:

(function() {
    // statements...
})();

Real world example, from glow.mozilla.com client-side code: https://github.com/potch/glow/blob/master/media/glow.js

What is this coding style used for? What's the difference between with and without the wrapped function style and when should it be used?

like image 754
Michael Avatar asked Mar 30 '11 22:03

Michael


1 Answers

Doing it like this ensures that none of the variables/function you define go into the global scope. All scripts you include in the page share the same global scope, so if you define two variables in two separate scripts with the same name, they actually refer to the same variable.

For example, suppose you have a.js and b.js, defined like so:

// a.js
var node = document.getElementById("something");

function frob() {
   node.style.display = "none";
}

// b.js
var node = document.getElementById("something-else");

If you include b.js after a.js in your page, then when you call frob it's going to hide the "something-else" node instead of the "something" node like you would expect.

Instead, you can do something like:

// a.js
(function() {
    var node = document.getElementById("something");

    window.frob = function() {
       node.style.display = "none";
    }
})();

// b.js
(function() {
    var node = document.getElementById("something-else");
})();

And the stuff inside b.js isn't going to interfere with what's in a.js.

Note that in reality I wouldn't add functions directly onto window, instead I would do something similar to what that glow.js script you linked to has: a single global variable that represents my scripts "namespace". In jQuery, for instance, that single global variable is $ (or jQuery).

like image 173
Dean Harding Avatar answered Nov 15 '22 15:11

Dean Harding