0
\$\begingroup\$

I'm learning about the Javascript module pattern from an array of online sources. The following suits my basic needs at the moment:

var module = function(){

    // Create the return module and its configuration
    var module = {},
    config = {
        css:{
            classes:{
                heading:'h1',
                navbar:'nav-bar'
            },
            ids:{
                widget:'widget',
                block:'block'
            } 
        },
        userName:'user',
        token:'UUID'
    };

    // Private methods
    function _moduleMethod() {
        console.log(config.userName);
    }

    // Add functionality to the module's init()-ialising method
    function init() {
        _moduleMethod();
    }

    // Add init, and any other methods, to obj
    module["init"] = init;

    // Return a the module as a Public API
    return module;

}();

// When the DOM is ready, run the module
document.addEventListener("DOMContentLoaded", function() {
    module.init();
});

My question is regarding the naming of the internal return object the same as the external variable "module". My thinking is that it's OK given closure and scoping but most of the examples I've seen name the internal object something like "obj" or "my". Am I going to run into issues down the line, say with the Augmenting module pattern?

\$\endgroup\$
1
\$\begingroup\$

Because of the scoping inside a closure you will not run into a problem.

The Revealing Module Pattern

I want to introduce this type of module pattern because it does not need the helper object module. Instead of collecting all public functions inside an object called module return directly an object with all public functions. This will reduce code and result in a better to reading code.

var module = function () {
    var config = {
        css: {
            classes: {
                heading: 'h1',
                navbar: 'nav-bar'
            },
            ids: {
                widget: 'widget',
                block: 'block'
            }
        },
        userName: 'user',
        token: 'UUID'
    };

    function _moduleMethod() {
        console.log(config.userName);
    }

    function init() {
        _moduleMethod();
    }

    // Return an object as public API
    return {
        init: init  
    }
}();
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.