dublintech
dublintech

Reputation: 17785

Do, inner and outer functions get their own copy of same variable?

just a bit confused by this code

var counter = function() {
    //...
    var count = 0;
    return function () {
        return count = count + 1;
    } 
}

var nextValue = counter();  
console.log(nextValue());
nextValue.count = 7;
console.log(nextValue());
console.log(nextValue.count);
console.log(nextValue());

Output is

1
2
7
3

It's counter intuitive. There are two representations of count. One on the outerfunction nextValue and one that only the inner anonymous function can see.

Correct, or are my missing something?

Upvotes: 1

Views: 101

Answers (2)

Pointy
Pointy

Reputation: 413727

The expression nextValue.count does not refer to the local variable "count" declared inside the function. It is not possible, in fact, to create a reference to a variable local to a function from code outside the function. What you're referencing there is simply a property of the function object.

So, yes, the "count" variable that the returned function has access to is effectively completely private to that function, and it is persisted in the closure formed by the call to the "counter" function.

If you did want that to work, you could do this:

function counter() {
  function actual() {
    return actual.count = actual.count + 1;
  }
  actual.count = 0;
  return actual;
}

edit — (fixed bogus code) the name "actual" inside gives the returned function safe access to the function object itself; originally I typed "this" there, and that would not work unless the external code set it up explicitly.

Upvotes: 4

rjz
rjz

Reputation: 16510

The way you describe it, count is effectively a private variable. When you're assign to nextValue.count, you're creating a separate property--not accessing the internal count being incremented by your counter.

Upvotes: 1

Related Questions