jeudi 10 septembre 2015

Two ways of implementing module pattern and `this` scope

I'm trying to learn a bit more about the module pattern and I've seem people implement it in two different ways.

Using a function for a module:

function Module(){
    var self = this;
    self.privateMethod = function () {
        self.someMethod();
    };

    self.someMethod = function () {
        $('#demo').on('click', function(){
            console.log(this.id);
            self.anotherMethod();
        });
    };

    self.anotherMethod = function () {
        //whatever
    };
}

And as an object:

var Module = {
    privateMethod: {
        this.someMethod();
    },

    someMethod: {
        $('#demo').on('click', function(){
            console.log(this.id); // `this` scope??
            this.anotherMethod();
        });
    },

    anotherMethod: {
      //whatever
    }
};

The last one seems to be more clear, but I'm not quite sure about the this scope in the someMethod compared with the function method, in which self is clearly separated from the scope of the variable this inside the jQuery event.

How could I clearly separate the scope of the this variable in the latest way of implementing the module pattern?

Which way of implementing it is more convenient?

Aucun commentaire:

Enregistrer un commentaire