Possible Duplicate:
What do parentheses surrounding a JavaScript object/function/class declaration mean?
I have found the following code in a website .
var testModule = (function(){
var counter = 0;
return {
incrementCounter: function() {
return counter++;
},
resetCounter: function() {
console.log('counter value prior to reset:' + counter);
counter = 0;
}
};
})();
So it follows the syntax var a = (blah balh..)()
What does it actually mean? What is the meaning of variable declaration like a =()()..
It’s defining a single-use function and executing it immediately. The code you provided is named the Module Pattern — see here for more information about its properties: http://www.yuiblog.com/blog/2007/06/12/module-pattern/
A normal function might be created like this:
And you could subsequently call it like so:
But in the example you provided, the function is both defined and executed once, and that function returns an object with two functions:
incrementCounterandresetCounter. You can call them like so:testModule.incrementCounter()andtestModule.resetCounter()The Module Pattern is useful when you have a single object and you want to encapsulate some properties which are only available to the functions defined in the closure.