TypeScript: Global static variable best practice

2020-06-30 08:32发布

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++;  
        }
      }
    }
    

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

标签: typescript
2条回答
疯言疯语
2楼-- · 2020-06-30 09:29

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

I prefer to do it this way:

module M {
  export class C {
    static count : number = 0;
    constructor() {
      C.count++;  
    }
  }
}
查看更多
\"骚年 ilove
3楼-- · 2020-06-30 09:33

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

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

module M {

  var count : number = 0;

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

  export class A{
  }
}
查看更多
登录 后发表回答