I'm reading the book secrets of the js ninja
, and very often I saw code like this
(function(){
something here;
})();
Why do we need to enclose the function within parentheses and why do we add one more pair of parentheses after that?
I'm reading the book secrets of the js ninja
, and very often I saw code like this
(function(){
something here;
})();
Why do we need to enclose the function within parentheses and why do we add one more pair of parentheses after that?
Its a self calling function, that invokes its self as the script finishes loading. You can call it without arguments, or you can add arguments to it such as window
or document
.
You use it in a way that jQuery use it:
(function( window, undefined ) {
// jQuery code
})(window);
An (almost) alternative syntax to do the same thing:
! function( window, undefined ){
// some code…
}(window);
Read more at: http://sarfraznawaz.wordpress.com/2012/01/26/javascript-self-invoking-functions/
This
(function(){
alert('hello');
})();
although it is a function is it called automatically so you dont/can't call it manually
These can be useful for for
loops like so
This will fail because i would be equal to 9 after 5 seconds
for(var i = 0; i < 10; i++) {
window.setTimeout(function(){
console.log(i);
}, 5000)
}
So you could do this
for(var i = 0; i < 10; i++) {
(function(a){
window.setTimeout(function(){
console.log(a);
}, 5000)
})(i);
}
Also good for creating a "private" scope like this
(function(){
var test = 'hello';
console.log( test ); // 'hello'
}());
console.log( test ); // 'undefined'
The last set of parentheses causes the function to execute immediately. A function is created and executed without ever assigning it anywhere. The reason one might wrap their code in a function like this is to encapsulate code. Take this for example:
var myVar = 'whatever';
function shout() { alert(myVar); }
Here, myVar
and shout
have just become global variables. You can open up your console and type window.myVar
or window.shout
and you'll be able to access and change those variables. By wrapping it in a function, those variables remain local to the outer function:
(function() {
var myVar = 'whatever';
function shout() { alert(myVar); }
})();
window.myVar
and window.shout
are undefined. The only exist inside that function.
The pattern is also used to create a closure around local variables. See JavaScript closure inside loops – simple practical example.
Self invoking function, basically it calls itself stright away.
Used normally to pass in a variable like jQuery to insure that $
is truly the jQuery object!
(function($){
// $ now is equal to jQuery
})(jQuery);
It runs the function you just created. The reason to do this is that it encloses all of the code you write within a new scope. This means when you define vars
and functions
, they will be kept within the scope of that function()
you just created.
In short, it encapsulates code.