I want to understand the way anonymous self invoking function is able to maintain the last updated state of variable but why is it not possible in case of normal anonymous functions .Both functions are closures still are behaving differently while maintaining the previous state of variable. ex:
var selfInvokingfunc= (function () {
var a=2;
var myprivatefunction = function () {
a=a+2;
console.log(a);
}
return {
mypublicfunction : function () {
myprivatefunction();
}
}
})();
selfInvokingfunc.mypublicfunction() ;//a is 4
selfInvokingfunc.mypublicfunction(); // a is 6
var nonSelfInvokingAnonymousFunction = function () {
var a=2;
var myprivatefunction = function () {
a=a+2;
console.log(a);
}
return {
mypublicfunction : function () {
myprivatefunction();
}
}
};
nonSelfInvokingAnonymousFunction().mypublicfunction(); //a is 2
nonSelfInvokingAnonymousFunction().mypublicfunction(); //a is 2
Same works fine for non self invoking if invoked as :
var temp=nonSelfInvokingAnonymousFunction();
temp.mypublicfunction() ; // a is 4
temp.mypublicfunction(); // a is 6
Please help me understand the same.
Every time the main body of the outer function is executed and the lines:
are run, a new binding for those variables are created in memory.
With the self-invoking function, since it's executed immediately and once, there then exists one binding for the
avariable, which themypublicfunctionproperty can see via the closure.In contrast, with your
nonSelfInvokingAnonymousFunction, every time you invoke it, you create a separate binding fora:When you have two separate bindings for the
avariable, callingmypublicfunctionon a function that closes over one of the bindings will have no effect on the other binding.In your last code, when you do
You create a single
a, and atempwhosemypublicfunctionfunction closes over that onea, so callingmypublicfunctionmultiple times results in thatachanging multiple times.