user56725
user56725

Reputation:

JavaScript: module pattern differences

What is the difference between

var module = (function(){
    return {} 
})()

and

(function(context){
    var module = {}
    context.module = module;
})(this)

Upvotes: 1

Views: 327

Answers (2)

Bergi
Bergi

Reputation: 664434

A property of this is not equivalent to a variable. In the global scope (i.e. where this references window), they are similiar. Yet, for example they will have a different behavior when you try to delete them:

> this.module = {};
> delete this.module
true
> var module = {};
// cant be deleted

Apart from that, both snippets create an empty object, wrapped inside a closure where you could define local (private) variables/functions etc. In your second function the object is also assigned to the local variable module, but that could be done in the first one as well.


@Eric: Your approach, using the new operator, is similiar to the first one regarding the variable. However, it will create an instance of that anonymous function instead of returning a plain object. It will inherit properties from a custom prototype, so for example module.constructor will then point to the anonymous function (which cannot be garbage collected, but e.g. even reused to create a clone). I would not recommend to use this.

Upvotes: 2

Mike Robinson
Mike Robinson

Reputation: 25159

Top one is revealing module pattern. It lets you define private functions (as much as you can in javascript) and choose which ones are made public via the return call.

var module = (function(){ 
    function foo() {}; // Public, since it's returned

    function bar() {}; // Private, since it is not returned

    return {
        foo: foo
    } 
})();

The bottom one, as far as I can tell, just assigns an object literal to another object's namespace. It's probably the start of a singelton pattern.

(function(context){
    var module = {};
    context.module = module;
}(this)

The module could actually be defined with the revealing module pattern, hard to say since in your example it's just an object literal.

Upvotes: -1

Related Questions