Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript modules: return a bare object, or name it

Using the Javascript module pattern, what are the advantages/dis-advantages of returning a bare object containing the interface, versus creating a named object containing the interface, then returning a reference? Example code below. I always put the interface into a named object, and the one advantage I see of this is I can do some debugging before I return it.

function bareObjectModule() {
    return {
        method1: function() {}
        //etc.
    }
}

function namedObjectModule() {
    var namedObjectModule = {
        method1: function() {}
    }

    //debug here?
    return namedObjectModule;
}
like image 478
Dexygen Avatar asked Jul 29 '26 09:07

Dexygen


1 Answers

The main advantage of returning the interface directly is that it is short and does not include much boilerplate but having a named reference is much more powerful and allows for other patterns that you could not originally. The biggest advantage is that it is much easier to have the functions reference each other if you have a reference to the module

var M = {};
M.f1 = function(){ ... };

M.f2 = function(){  M.f1() }; //functions can reference each other without
                              // a fragile dynamic binding through `this`

M.f3 = some_combinator(M.f2); //since you are not limited to defining things as 
                              //property-value pairs you have much more flexibility..

return M;
like image 186
hugomg Avatar answered Aug 01 '26 00:08

hugomg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!