JohnMerlino
Programmer
I was reading an article where they reference the below code and say "There is not a single closure per function declaration. There is a closure for each call to a function." Can anyone interpret that?
Also, in the below code, when we call closure1(5), how does the newClosure constructor know to receive it as parameter x, rather than receive it as someNum or someRef parameters?
Thanks for any response.
Also, in the below code, when we call closure1(5), how does the newClosure constructor know to receive it as parameter x, rather than receive it as someNum or someRef parameters?
Code:
function newClosure(someNum, someRef) {
// Local variables that end up within closure
var num = someNum;
var anArray = [1,2,3];
var ref = someRef;
return function(x) {
num += x;
anArray.push(num);
alert('num: ' + num +
'\nanArray ' + anArray.toString() +
'\nref.someVar ' + ref.someVar);
}
}
closure1 = newClosure(40, {someVar: 'closure 1'});
closure1 = newClosure(10000, {someVar: 'closure 2'});
closure1(5); //Our object at this point,
closure2(-10);
Thanks for any response.