Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

JavaScript Closures question

Status
Not open for further replies.

JohnMerlino

Programmer
Jun 13, 2010
1
US
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?

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.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top