Following are two ways to define BW.Timer. Can someone tell me what the difference is? I am not certain the first is even valid, but if it is valid, what is different about using the myfunc=(function(){}()) syntax?
BW.Timer = (function () {
return {
Add: function (o) {
alert(o);
},
Remove: function (o) {
alert(o);
}
};
} ());
And…
BW.Timer = function () {
return {
Add: function (o) {
alert(o);
},
Remove: function (o) {
alert(o);
}
};
};
The first is the return-value of the immediately-invoked function. The second is a function. It essentially comes down to what the difference is between these:
Since the first function is called immediately, the value of 0 is given to the variable
f. The firstfis not a function. However, the secondfwe must call in order to get the value:It follows that in your example, the first
BW.Timeris the object literal itself and the second is a function returning an object literal. You must call the function in order to get to the object:Why use the first then?
You might ask yourself why one would use a syntax like
a = (function() { return {}; })()instead ofa = {}, but there’s a good reason. An IIFE (Immeditately-Invoked Function Expression), unlike a regular function allows the emulation of static variables (variables that maintain their value through a single instance). For example:The above a text-book example of the Module Pattern. Since the function is called right away, the variable
xis instantiated and the return value (the object) is given tomodule. There’s no way we can get toxother than by using thegetandsetmethods provided for us. Therefore,xis static, meaning its variable won’t be overridden each time you usemodule.On the other hand, let’s see an example where
moduleis declared as a function instead:When we call
module()thexvariable is overridden each time. So we’re effectively using different instances ofmoduleandxeach time we callmodule.