0

I am learning about module patterns, a bit confused about how they behave.

So, I have this simple module,

var testModule = (function() {

    //private counter
    var counter = 0;
    return {
        //public methods
        incrementCounter: function () {
            console.log(counter++);
        },
        resetCounter: function () {
            counter = 0;
        }
    };
}());

From what I have understood till now(and please correct me if I am wrong), the above function will be invoked immediately(because of the parentheses).

When it runs, it returns an object, which contains only the public methods defined.

So, in the end, after executing the above function our code will look something like this internally (Please, please correct me if I am wrong. this is only my understanding of its behaviour)

testModule_ = {
    incrementCounter: function () {
        return counter++; 
    },
    resetCounter: function () {
        console.log("counter value prior to reset: " + counter);
        counter = 0;
    }
};

The thing which I don't understand is, when we access the public methods as testModule.incrementCounter() or testModule.resetCounter(), how do they get the value of the counter, as testModule now doesn't have counter?

I can see it gets the value for the first time, as when that anonymous function was self invoked, it did increment counter and reset the values. But what about second time, from where it gets the value of counter?

I hope I am clear. Thanks in advance.

software_writer
  • 3,941
  • 9
  • 38
  • 64
  • By magic, err, …closure! – Bergi Feb 28 '16 at 20:20
  • It's called a closure. The functions have a *permanent* reference to their enclosing variable scope, so as long as at least one of those functions continues to exist, the `counter` variable will exist and be accessible from those functions. –  Feb 28 '16 at 20:20
  • Thank you for the explanation! – software_writer Feb 28 '16 at 22:45

0 Answers0