我正在处理一个项目,我们使用一种模式来定义“模块”(即实际上是公共静态类),其中每个模块都有一个init()
函数,该函数应在模块被定义后调用。它看起来像这样:
MyNamespace.MyModule = (function () {
var my = {};
my.init = function(config) {
// setup initial state using config
};
return my;
})();
我看到这段代码中有两种定义config
默认值的模式,想知道哪一种更好——是否存在我没有立即发现的优缺点。有什么建议吗?
以下是第一种:
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;
})();
以下是第二个内容:
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;
})();