- Learning TypeScript 2.x
- Remo H. Jansen
- 289字
- 2025-04-04 17:02:05
Static members
We can use the static keyword to enable the usage properties and methods in a class without needing to create an instance of it:
class TemperatureConverter { public static CelsiusToFahrenheit( celsiusTemperature: number ) { return (celsiusTemperature * 9 / 5) + 32; } public static FahrenheitToCelsius( fahrenheitTemperature: number ) { return (fahrenheitTemperature - 32) * 5 / 9; } }
As we can observe in the preceding code snippet, the TemperatureConverter class has two static methods named CelsiusToFahrenheit and FahrenheitToCelsius. We can invoke these methods without creating an instance of the TemperatureConverter class:
let fahrenheit = 100; let celsius = TemperatureConverter.FahrenheitToCelsius(fahrenheit); fahrenheit = TemperatureConverter.CelsiusToFahrenheit(celsius);
When a method or property is not static, we refer to it as an instance method or an instance property. It is possible to declare classes that have both static and instance methods or properties:
class Vector3 { public static GetDefault() { return new Vector3(0, 0, 0); } public constructor( private _x: number, private _y: number, private _z: number ) {} public length() { return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z ); } public normalize() { let len = 1 / this.length(); this._x *= len; this._y *= len; this._z *= len; } }
The preceding class declares a vector in a 3D space. The vector class has instance methods to calculate the length of the vector and to normalize it (change its length to 1 without changing its direction). We can create instances of the class using the class constructor and the new keyword:
const vector2 = new Vector3(1, 1, 1); vector2.normalize();
However, the class also has a static method named GetDefault, which can be used to create a default instance:
const vector1 = Vector3.GetDefault(); vector1.normalize();