如何改进我的Javascript Build Config Class?

时间:2012-05-26 00:25:56

标签: javascript

我对JavaScript不是很好。我正在尝试编写一个构建配置类,可用于动态设置设置。我们的想法是传入要运行的环境,然后正确设置变量。我有以下内容:

function BuildConfig(){  
    this.build = 'html5';
    this.server = 'http://someurl',
    this.nfc = true,
    this.barcode = true,
    this.scheduler = true,
    this.getConfig = function(buildType){  

     switch(buildType)
        {
        case "ios":
            this.build = 'ios';
            this.server = 'http://someurl';
            this.nfc = true;
            this.barcode = false;
            this.scheduler = false;
            break;
        case "android":
            this.build = 'android';
            this.server = 'http://someurl';
            this.nfc = false;
            this.barcode = true;
            this.scheduler = false;
            break;
        case "websiteanonymous":
            this.build = 'websiteanonymous';
            this.server = 'http://someurl';
            this.nfc = true;
            this.barcode = false;
            this.scheduler = true;
            break;
        case "website":
            this.build = 'website';
            this.server = 'http://someurl';
            this.nfc = true;
            this.barcode = true;
            this.scheduler = false;
            break;

        default:

        }

    };  
}; 

这看起来不错吗?可以做出任何改进吗?

由于

2 个答案:

答案 0 :(得分:1)

你的方法还可以。以下代码略短:

function BuildConfig(type) {
    // Defaults
    this.build = 'html5';
    this.server = 'http://someurl';
    this.nfc = true;
    this.barcode = false;
    this.scheduler = false;

    switch (type) {
        case "ios":
            this.build = 'ios';
            this.scheduler = true;
            break;

        case "android":
            this.build = 'android';
            this.server = 'http://anotherurl';
            this.nfc = false;
            break;

        case "websiteanonymous":
            this.build = 'websiteanonymous';
            this.server = 'http://otherurl';
            this.barcode = true;
            break;

        case "website":
            this.build = 'website';
            break;
    }
}

var config = new BuildConfig('android');

答案 1 :(得分:0)

你似乎在重复自己,在所有情况下(默认除外)你都有相同的值:

        ...
        this.server = 'http://someurl';
        this.nfc = true;
        this.barcode = true;
        this.scheduler = true;
        ...

我建议:

  • 创建一个标志var并使用它来应用更改
  • 或,自动进行更改并在case default
  • 中还原