Revealing module pattern

by Richard Hunter

HTML

<h1>Revealing module pattern</h1>

<ol>
    
    <li>factory function 'mymodule' returns an object literal 
        on each call.</li>
    <li>dependencies are passed in as arguments</li>
    <li>defaults object is overwritten by any overrides in config object</li>
    <li>private functions have access to private properties object</li>
    <li>public methods can access each other through 'this' keyword and can access private properties and functions</li>
    
</ol>
<h2>Advantages</h2>
<p>
    Provides a closure which contains private variables and functions. 
</p>
<h2>Disadvantages</h2>
<p>
    Cannot take advantage of prototypical inheritance.
</p>

JavaScript

function NSI(name, obj) {
    window[name] = obj;
}
NSI("processText", function (text) {
    console.log("processing text: %s, thanks", text);
});
NSI("doAlert", function (text) {
    alert(text);
});

NSI("mymodule", function (dep1, dep2, config) {
    
    var dep1 = dep1;
    var dep2 = dep2;
    
    var defaults = {
        name : "default name",
        address : "default address"
    };
    
    var props = _.extend(defaults, config);
    
    function privateMethod() {
    
        console.log("private property: %s", props.address);
    }

    return {    
        doThis : function () {          
            dep1(props.name);
        },  
        doThat : function () {
            this.doThis();
        },
        doAlert : function (text) {
            dep2(text);
        },
        callPriv : function () {
            privateMethod();
        }
    };
});

var configObj = {
    name : "this is my real name"
};

var mod = mymodule(processText, doAlert, configObj);

mod.doThat();
mod.doAlert("blah blah");
mod.callPriv();