Search code examples
javascriptjavascript-objectsmodule-pattern

Understanding the benefit of naming a returned object in the module pattern in JavaScript


I understand stylistically why you would name a returned object, for organization etc. However, I don't understand the benefit of adding or removing methods or the ability to update properties at runtime.

var foo = (function(){
    var publicAPI = {
        bar: function(){
            publicAPI.baz();
        },
        baz: function(){
            console.log("baz");
        }
    };
    return publicAPI;
})();

Solution

  • Typically, the public api will have access to a variable inside of the closure and will be the exclusive way to access the value(s).

    You example above is superfluous since the api can only access the object returned, but if you add another variable that only publicAPI can access, then you have created privacy.

    var foo = (function(){
        //private 
        var _foo = {name: 'Foo'};
        var publicAPI = {
            getName: function(){
                return _foo.name;
            },
            setName: function(name){
                _foo.name = name;
            },
        };
        return publicAPI;
    })();