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?

서영빈 :

May be it's just difference of using '( ) ' . '( )' means you're gonna execute (or open) the variable or function before the bracket.

Adjust the codes a little 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);
    }
  }
})();
counter.increase()
counter.increase()
counter.increase()
counter.show()

Then it returns '3'. The only difference is the use of "()". If you don't use '()', it mean you're not gonna execute it. So you can just handle already opened context.

Guess you like

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