Static Properties and Methods
1234567891011class MathHelper { static pi: number = 3.14159; static calculateCircleArea(radius: number): number { return MathHelper.pi * radius * radius; } } // Accessing static members without creating an instance console.log(MathHelper.pi); // 3.14159 console.log(MathHelper.calculateCircleArea(5)); // 78.53975
When working with classes in TypeScript, you will encounter both static and instance members. Static members belong to the class itself, not to any specific object created from that class. You access static properties and methods using the class name, not through an instance. For example, MathHelper.pi and MathHelper.calculateCircleArea() are both accessed directly from the class.
In contrast, instance members are tied to individual objects created from the class. You must create an instance with new before you can access these members.
Use static members when you need functionality or data that is shared by all instances of a class, or when the data does not depend on instance-specific information. Common examples include:
- Utility methods;
- Constants;
- Counters that are relevant to the class as a whole.
Takk for tilbakemeldingene dine!
Spør AI
Spør AI
Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår
Awesome!
Completion rate improved to 5
Static Properties and Methods
Sveip for å vise menyen
1234567891011class MathHelper { static pi: number = 3.14159; static calculateCircleArea(radius: number): number { return MathHelper.pi * radius * radius; } } // Accessing static members without creating an instance console.log(MathHelper.pi); // 3.14159 console.log(MathHelper.calculateCircleArea(5)); // 78.53975
When working with classes in TypeScript, you will encounter both static and instance members. Static members belong to the class itself, not to any specific object created from that class. You access static properties and methods using the class name, not through an instance. For example, MathHelper.pi and MathHelper.calculateCircleArea() are both accessed directly from the class.
In contrast, instance members are tied to individual objects created from the class. You must create an instance with new before you can access these members.
Use static members when you need functionality or data that is shared by all instances of a class, or when the data does not depend on instance-specific information. Common examples include:
- Utility methods;
- Constants;
- Counters that are relevant to the class as a whole.
Takk for tilbakemeldingene dine!