JavaScript 模块模式:默认值

JavaScript module pattern: default values

本文关键字:默认值 模式 模块 JavaScript      更新时间:2023-09-26

我正在做一个项目,我们使用一种模式来定义"模块"(即有效的公共静态类),其中每个模块都有一个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;
})();

没有太大区别,这实际上完全取决于您可读的内容。 我个人喜欢第二种方法,因为它将默认值与逻辑分开。