Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

where does this variable come from

Tags:

javascript

This is from How do JavaScript closures work?. The first answer makes zero sense to me and I can't comment on it. It is extremely frustrating

function foo(x) {
  var tmp = 3;
  return function(y) {
    alert(x + y + (++tmp));
  }
}
var bar = foo(2); // bar is now a reference to the closure returned by foo
bar(10);

What does this mean? Where does the y variable come from?

like image 203
Jessica Shu Avatar asked Jun 30 '13 22:06

Jessica Shu


2 Answers

For where the variables come from:

function foo(x) {       // x introduced
  var tmp = 3;          // tmp introduced
  return function (y) { // y introduced
    // Can access all variables in scope, as introduced above.
    // However, ONLY x and tmp are closed-over as y is just a parameter
    // to the inner function.
    alert(x + y + (++tmp));
  }
}

var bar = foo(2);  // 2 is value for x
bar(10);           // 10 is value for y

Now, looking a bit deeper:

foo(2) returns a new function-object (the inner function) which is bound to two variables (x which currently has the value 2, and tmp which currently has the value 3).

Then bar(10) runs that function-object passing in 10 (which is then the value of y).

Calling bar(10) repeatedly will result in different values as a closed-over variable tmp is re-assinged (++tmp) during the function invocation.

like image 168
user2246674 Avatar answered Oct 06 '22 17:10

user2246674


You need to distinguish between variables (a name for a piece of memory containing information) and parameters (placeholder for a variable to be passed into a function). (Actually it's called a formal parameter in the prototype of the function and an actual parameter when used in the function body.) So y is not an existing variable but a placeholder for a variable (or value) to be passed in.

You then need to understand that var func = function(){} turns func into a reference to an anonymous function (a function without a name). A simplified example would be:

var func = function (y) {
   alert(y);
}
func("hello");

You can work up from that. Everything else is just the same principle applied in a way of nesting.

like image 37
zany Avatar answered Oct 06 '22 15:10

zany