I often see the following code:
(function () {
// init part
})();
but I never could get my head around how it works. I find the last brac
That pattern will create a new execution context (EC) in which any local variable objects (VO's) will live, and will likewise die when the EC exits. The only exception to this lifetime is for VO's which become part of a closure.
Please note that JavaScript has no magic "init" function. You might associate this pattern with such since most any self-respecting JS library (jQuery, YUI, etc.) will do this so that they don't pollute the global NS more than they need to.
A demonstration:
var x = 1; // global VO
(function(){
var x = 2; // local VO
})();
x == 1; // global VO, unchanged by the local VO
The 2nd set of "brackets" (those are actually called parens, or a set of parentheses), are simply to invoke the function expression directly preceding it (as defined by the prior set of parenthesis).
The code creates an anonymous function, and then immediately runs it. Similar to:
var temp = function() {
// init part
}
temp();
The purpose of this construction is to create a scope for the code inside the function. You can declare varaibles and functions inside the scope, and those will be local to that scope. That way they don't clutter up the global scope, which minimizes the risk for conflicts with other scripts.
I can't believe no-one has answered the ops question!
The last set of brackets are used for passing in the parameters to the anonymous function. So, the following example creates a function, then runs it with the x=5 and y=8
(function(x,y){
//code here
})(5,8)
This may seem not so useful, but it has its place. The most common one I have seen is
(function($){
//code here
})(jQuery)
which allows for jQuery to be in compatible mode, but you can refer to it as "$" within the anonymous function.
Its is called immediatly invoking function expression (IIFE). Mainly associated with the JavaScript closure concept. Main use is to run the function before the global variable changed, so that the expected behaviour of code can be retained.
In simple word you can understand that whenever page load, by this second pair of brackets () function will have called default.We need not call the function.It is known as anonymous function.
i.e.
(function(a,b){
//Do your code here
})(1,2);
It same like as
var test = function(x,y) {
// Do your code here
}
test(1,2);
Self invoking anonymous function (SIAF)
Self-invoking functions runs instantly, even if DOM isn't completely ready.
jQuery document.ready vs self calling anonymous function