javascriptmodule-pattern

JS module pattern: why assignment in extending?


I see a lot of code here, here:

var module = (function (module) {
    module.prototype.something_else = function () {
    };
    return module;
})(module);

Why var module = part present at all? And why return module; if previous part is not needed?

I see usage of:

var module = (function(module) {...})(module || {});

for cases when module wasn't already defined sometimes... Is that above case?


Solution

  • This block of code is only used if module is already defined and you want to extend it (e.g., add a new method):

    var module = (function (module) {
        module.prototype.something_else = function () {
        };
        return module;
    })(module);
    

    It accepts module as an input parameter and returns the extended module. The assignment of var module = then replaces the original module.

    Answering your questions one by one:

    Why var module = part present at all?

    In the example above (taken from your first URL), var module = is not necessary. The simple example they provide is silly. You could accomplish the exact same thing with this:

    module.prototype.something_else = function () {};
    

    Using the above pattern to extend a class makes more sense with the examples provided in your second URL ( http://www.adequatelygood.com/JavaScript-Module-Pattern-In-Depth.html ):

    var MODULE = (function (my) {
        var old_moduleMethod = my.moduleMethod;
    
        my.moduleMethod = function () {
            // method override, has access to old through old_moduleMethod...
        };
    
        return my;
    }(MODULE));
    

    Immediate executing function creates a new scope where we can preserve the old method var old_moduleMethod = my.moduleMethod;

    Next question:

    And why return module; if previous part is not needed?

    You need return module because otherwise the function wouldn't return anything and the var module = assignment would be set to an undefined value.

    Next question:

    for cases when module wasn't already defined sometimes... Is that above case?

    Yes, that is the case. If module isn't defined then you would need to pass in an empty object. However, you typically would use a pattern to extend an object if it isn't defined in the first place. That would make no sense and would just complicate your code.