1

我不太擅长 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:

        }

    };  
}; 

这看起来好吗?可以做任何改进吗?

谢谢

4

2 回答 2

1

Your approach is ok. And the below code is slightly shorter:

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');
于 2012-05-26T01:04:48.980 回答
0

看来你重复自己太多了,在所有情况下(除了default)你都拥有相同的值:

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

我建议这样做:

  • 创建一个标志 var 并使用它应用更改
  • 或者,自动进行更改并恢复case default
于 2012-05-26T00:39:27.617 回答