Module Pattern - JavaScript

I've been working on multiple types of JavaScript projects. Most of time, with the module pattern, it is very easy to expedite my work. I would like to share the one I used most here:

var MODULE = (function(window, $, MODULE, undefined) {

    MODULE.Public = {};

    MODULE.Public.init = function() {
        privateFunc();
    };

    function privateFunc() {
        try {
            afunc();
        } catch(e) {
            log(e);
        }
    }

    function log(envelope) {
        if (DEBUG_MODE)
            throw envelope;
        console.log("GeniusCarrier: " + envelope.message);
    }

    var DEBUG_MODE = false;

    return MODULE;
})(window, jQuery, MODULE || {});

Here is another module pattern, which I use less, but also very popular:

var MODULE = (function() {

    var privateVar = 0, privateMethod = function(foo) {
        console.log(foo);
    };

    return {
        publicVar : "foo",
        publicFunction : function(bar) {
            privateVar++;
            privateMethod(bar);

        },
        anotherPublicFunction : function() {
            publicFunction(publicVar);
        }
    };

})(); 

Yang Zhao

Read more posts by this author.


Comment