Difference between substitution and original function var

yubin :

Thank you for help. Sorry for not knowing the exact name of the concept I'm using.

I have a function like this.

var counter = function() {
  var count = 0;
  function changeCount(number) {
    count += number; 
  }
  return {
    increase: function() {
      changeCount(1);
    },
    decrease: function() {
      changeCount(-1);
    },
    show: function() {
      alert(count);
    }
  }
};

Now, I'm gonna make '3' with this function, and there seems two ways.

1)

counter().increase()
counter().increase()
counter().increase()
counter().show()

I guessed this would throw out '3', but the answer was '0'.

2)

var another = counter();
another.increase();
another.increase();
another.increase();
another.show()

Now it returns '3' for answer. And here's my question. Literally, the variable "another" is just the same with "counter()". Then, WHY the answers come different?

The former code (counter().increase() ) seems to return 'count' back to 'o' after every 3 lines of 'counter().increase()'. Whereas 'another.increase()' seems to cumulate the change of variable 'count'. The difference between two codes is just saying "variable 'another' is the same with counter()". And why is this leading to such different answer?

Quentin :

Look at what the counter function does.

It creates a variable, sets it to 0, then returns some functions.

If you call counter once, it does that once. If you call it three times, it does that three times.

(and then you call .increase() on the return value … and in your first example that's the three different things but in the second, it is the same thing each time).


Or to put it another way.

If, every time you called counter you took a clean sheet of paper and put it down in front of you. And every time you called increase you drew a tick on the piece of paper in front of you.

You'd either end up with three pieces of paper with a tick on each, or one piece of paper with three ticks.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=279085&siteId=1