Unknown JavaScript syntax might be related to closures
I found some JavaScript syntax which is unknown for me and I even don't know how it's called or开发者_开发问答 what it does so I can't find any documentation.
I found it on MDC Doc Center:
var Counter = (function() {
var privateCounter = 0;
function changeBy(val) {
privateCounter += val;
}
return {
increment: function() {
changeBy(1);
},
decrement: function() {
changeBy(-1);
},
value: function() {
return privateCounter;
}
}
})();
The part I am interested in is:
var Counter = (function() {})();
What the round brackets do? How this is called and where it can be used?
(function() {})()
is an immediately executed function.
This creates private scope around a block of code. This also can create a closure which can be useful to maintain state after the function ends.
You require ()
around function() {}
because function() {}()
is an illegal statement (the JS parser fails).
Also it is a habit to make sure you wrap an immediately executed function in ()
so that readers of your code are aware they should be interested in the return value of the function instead of the function.
It's the module pattern. It's usually used to create singletons. See this answer:
What is this design pattern known as in JavaScript?
Consider when you have a function called a:
function a() {
alert("hi");
}
You call it like this:
a();
In (function() {})()
you're just skipping the part where you defined the function before-hand. In one fell swoop, you've defined an unnamed function and called it.
精彩评论