dimanche 28 février 2016

How does this module pattern in Javascript work? [duplicate]

This question already has an answer here:

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.

Aucun commentaire:

Enregistrer un commentaire