I think this is a silly question, but given this JavaScript code....
function outerFun()
{
var a=0;
function innerFun()
{
a++;
alert(a);
}
return innerFun;
}
var obj=outerFun();
obj(); //1
obj(); //2
var obj2=outerFun();
obj2(); //1
obj2(); //2
I understand why the result is 1 and then 2 in the first two calls of obj(), but I am confused as to why obj2() is returning 1 and not returning 3 after calling obj() twice.
3 Answers 3
Because each time you call outerFun(), you are creating a different and new execution context, and so innerFun isn't really the same thing, as each function reference to innerFun you return from outerFun is in a different context, a context with its own variables.
function outerFun()
{
var a=0;
function innerFun()
{
a++;
alert(a);
}
return innerFun;
}
var obj = outerFun();
var obj2 = outerFun();
console.log(obj === obj2);
// Not equal, because innerFun is a different innerFun for each function call,
// as it is the same function name, returned from the same function,
// but in a different context.
obj(); //1
obj(); //2
obj2(); //1
obj2(); //2
// Call obj twice, it'll increase to 4.
// While calling obj2 once again, leaves it at 3.
// This way you can know that obj and obj2 are not modifying
// the same variables.
// They are independent of each other.
obj(); // 3
obj(); // 4
obj2(); // 3
Comments
When you run outerFun(), it creates a new function and returns it. It does this every time you call it. And each function it returns is actually a brand new function, unrelated to the ones created when you called it before, even though the code inside them is the same.
When you reach this statement...
var obj2=outerFun();
...you're actually creating a new object that has its own copy of a in its parent scope. So you actually would get three if you called obj(); again after instantiating obj2. They each have their own a variable. Hopefully this modification to the example makes sense:
function outerFun()
{
var a=0;
function innerFun()
{
a++;
alert(a);
}
return innerFun;
}
var obj=outerFun();
obj(); //1
obj(); //2
var obj2=outerFun();
obj(); //3
obj(); //4
obj2(); //1
obj2(); //2
obj(); //5
Make sense?
Comments
When you are doing outerfun () second time, new a is defined with value 0.