我对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:
}
};
};
这看起来不错吗?可以做出任何改进吗?
由于
答案 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;
...
我建议:
case default