2013-05-09 103 views
23

我有這個類,每次類實例化時都需要增加一個數字。 我發現兩種方法來這個地方兩種方式的工作原理,但我還沒有確定什麼是最好的做法TypeScript:全局靜態變量最佳實踐

  1. 聲明變量在模塊範圍

    module M { 
        var count : number = 0; 
        export class C { 
        constructor() { 
         count++; 
        } 
        } 
    } 
    
  2. 聲明變量在類範圍和訪問它的類

    module M { 
        export class C { 
        static count : number = 0; 
        constructor() { 
         C.count++; 
        } 
        } 
    } 
    

我的看法是Ë xample兩個,因爲它不會在模塊範圍中添加count變量。

參見:C# incrementing static variables upon instantiation

回答

21

絕對方法2,因爲這是使用可變的類。所以它應該包含它。

在案例1中,你使用的是可變的,這將變得混亂,一旦你在那裏有一個以上的類如:

module M { 

    var count : number = 0; 

    export class C { 
    constructor() { 
     count++; 
    } 
    } 

    export class A{ 
    } 
} 
+1

如果C類是沒有用我不會打擾在封裝級看到它的計數唯一的一個。更重要的是變量名稱。在代碼中的大部分地方,「count」這個名稱並不足以說明它代表什麼。我更喜歡'numConstructed'或'structuredCount'。 – 2013-05-09 15:31:20

+0

同意,他們應該具體!這裏使用的代碼只是例子 – 2013-05-09 20:50:08

1

他們兩人都是好的,但method 2更多的自我解釋,這意味着它的少當你的代碼變得更加複雜,除非你每次使用count來增加你從這個模塊實例化一個類,然後method 1是要走的路。

我喜歡做這樣說:

module M { 
    export class C { 
    static count : number = 0; 
    constructor() { 
     C.count++; 
    } 
    } 
}