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
declare the variable in the module scope
module M { var count : number = 0; export class C { constructor() { count++; } } }
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
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 thecount
to increase each time you instantiate a class from that module thenmethod 1
is the way to go.I prefer to do it this way:
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: