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?
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
).
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