TypeScript:全局静态变量最佳实践

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16462839/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 01:04:24  来源:igfitidea点击:

TypeScript: Global static variable best practice

typescript

提问by Thomas Andersen

I have this class where I need to increment a number each time the class is instantiated. I have found two ways to this where both ways works, but I am not sure yet on what is the best practice

我有这个类,每次实例化该类时我都需要增加一个数字。我找到了两种方法,两种方法都可以使用,但我不确定什么是最佳实践

  1. declare the variable in the module scope

    module M {
      var count : number = 0;
      export class C {
        constructor() {
          count++;
        }
      }
    }
    
  2. declare the variable in the class scope and access it on Class

    module M {
      export class C {
        static count : number = 0;
        constructor() {
          C.count++;  
        }
      }
    }
    
  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++;  
        }
      }
    }
    

My take is example two as it does not adds the count variable in the module scope.

我的做法是示例二,因为它没有在模块范围内添加计数变量。

See also: C# incrementing static variables upon instantiation

另请参阅:C# 在实例化时增加静态变量

采纳答案by basarat

Definitely method 2 since that is the class that is using the variable. So it should contain it.

绝对是方法 2,因为那是使用变量的类。所以它应该包含它。

In case 1 you are using a variable that will become confusing once you have more than one classes in there e.g:

在第 1 种情况下,您使用的变量会在您有多个类时变得混乱,例如:

module M {

  var count : number = 0;

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

  export class A{
  }
}

回答by Mustafa Dwekat

Both of them are okay, but method 2more self explanatory, which means its less confusing when your code get more complex unless you are using the countto increase each time you instantiate a class from that module then method 1is the way to go.

它们都可以,但method 2更不言自明,这意味着当您的代码变得更复杂时,它不会那么令人困惑,除非您count每次从该模块实例化一个类时都使用增加,然后method 1才是要走的路。

I prefer to do it this way:

我更喜欢这样做:

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