如何改进我的 Javascript Build Config 类

How can i improve my Javascript Build Config Class?

本文关键字:Config Build Javascript 何改进 我的      更新时间:2023-09-26

我对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:
        }
    };  
}; 

这看起来还行吗?可以进行任何改进吗?

谢谢

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

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');

似乎你重复自己太多了,在所有情况下(除了默认值),你都有这些具有相同的值:

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

我建议这样做:

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