簡體   English   中英

如何改善Javascript Build Config類?

[英]How can i improve my Javascript Build Config Class?

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

似乎您重復太多了,在所有情況下( default除外),您都具有相同的值:

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

我建議這樣做:

  • 創建一個標志var並使用它來應用更改
  • 或者,自動進行更改並在case default還原

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM