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
A global variable can be accessed from anywhere inside the program while a static variable only has a block scope. So, the benefit of using a static variable as a global variable is that it can be accessed from anywhere inside the program since it is declared globally.
A static variable can be either a global or local variable. Both are created by preceding the variable declaration with the keyword static. A local static variable is a variable that can maintain its value from one function call to another and it will exist until the program ends.
A global variable's scope is in all the files, while a static global variable's scope is just the file where it is declared.
To declare a global variable in TypeScript, create a . d. ts file and use declare global{} to extend the global object with typings for the necessary properties or methods.
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{ } }
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++; } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With