JavaScript Module Pattern: Default Values
I am working on a project in which we use a template to define "modules" (ie effectively public static classes) where each module has init()
to be called after the module has been defined. It looks like this:
MyNamespace.MyModule = (function () {
var my = {};
my.init = function(config) {
// setup initial state using config
};
return my;
})();
I see two patterns in this codebase for the config
default definition and wonder which one might be better - if there are any advantages or disadvantages that I don't see right away. Recommendations?
Here's the first one:
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;
})();
+3
source to share