Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript module pattern: default values

I'm working on a project where we use a pattern to define "modules" (i.e. effectively public static classes), where each module has an init() that should be called once the module has been defined. It looks like:

MyNamespace.MyModule = (function () {
    var my = {};
    my.init = function(config) {
        // setup initial state using config
    };
    return my;
})();

I'm seeing two patterns in this code base for defining config defaults and wondering which one might be better—if there's any advantage or disadvantage that I'm not immediately seeing. Recommendations?

Here's the first:

MyNamespace.MyModule = (function () {
    var my = {}, 
        username,
        policyId,
        displayRows;

    my.init = function(config) {
        config = config || {};
        username = config.username || 'Anonymous';
        policyId = config.policyId || null;
        displayRows = config.displayRows || 50;
    };

    return my;
})();

And here's the second:

MyNamespace.MyModule = (function () {
    var my = {}, 
        username = 'Anonymous',
        policyId = null,
        displayRows = 50;

    my.init = function(config) {
        config = config || {};
        username = config.username || username;
        policyId = config.policyId || policyId;
        displayRows = config.displayRows || displayRows;
    };

    return my;
})();
like image 962
barfoo Avatar asked Mar 25 '26 18:03

barfoo


1 Answers

There isn't much of a difference, it's really all about what's readable to you. I personally like the 2nd method because it separates the defaults from the logic.

like image 107
Robert Messerle Avatar answered Mar 27 '26 09:03

Robert Messerle



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!