bingjie2680
bingjie2680

Reputation: 7773

Javascript module pattern

what is the difference below:

function test(){
    this.init=function(){//do something}
    this.some=function(){//do something}
    function other(){}
}

and

function test(){
    function init(){//do something}
    function some(){//do something}
    function other(){}

    return {'init':init, 'some':some};
}

Thanks for explanation.

Upvotes: 1

Views: 226

Answers (2)

hugomg
hugomg

Reputation: 69934

As Mike has already pointed out, there is a difference on how they need to be invoked (the first version requires new while the second doesn't).

That said, if these are being used for actual modules (instead of just objects) and the functions in the module call each other then there is a difference.

In the second case the functions can reference each other directly (static binding).

function init(){
    some(17);
}

But in the first case they would reference each other via dynamic binding through the this:

this.init = function(){
    this.some(17); 
}

This means that in the first case (with the this) the init function must be always called as module.init() and cannot be passed to a callback

setTimeout( module.init, 1000 );
//this line will does not work with the `this.init` variation
//but will work fine in the second version

Because I don't like having to retype the function names as in the second version, I personally prefer to use the following style in my modules:

var module = (function(){

    var M = {}; //private namespace.
                //decouples from the actual name and I
                //can always use the same letter (for consistency)

    M.init = function(){
        M.some(17);
    };

    M.some = function(){
        //
    }

    function other(){ ... }

    return M;
}());

Upvotes: 4

Joe
Joe

Reputation: 82594

The first example:

var object = new test();
object.init();

the second example:

var object = text(); // no new
object.init();

Upvotes: 6

Related Questions