3

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;
})();
2
  • The second example follows best practices by initializing your members and then using their default values as the defaults if nothing is supplied in the config. Commented Apr 10, 2012 at 16:21
  • 3
    The second variant is also better if default parameters can contain complex objects as subparameters. Commented Apr 10, 2012 at 16:23

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.