static
关键字的主要作用定义类级别的属性和方法:
static
关键字,可以在类中定义静态属性和方法。这些属性和方法可以在不创建类实例的情况下直接访问。共享属性或方法:
class Counter {
static count: number = 0;
static increment() {
Counter.count++;
}
static getCount(): number {
return Counter.count;
}
}
console.log(Counter.getCount()); // 输出: 0
Counter.increment();
console.log(Counter.getCount()); // 输出: 1
解释:
Counter
类中定义了一个静态属性 count
和两个静态方法 increment
和 getCount
。count
是一个共享的计数器,increment
方法用于增加计数,getCount
方法用于获取当前的计数值。Counter
来访问静态属性和方法,而不需要创建类的实例。class MathHelper {
static square(x: number): number {
return x * x;
}
static cube(x: number): number {
return x * x * x;
}
}
console.log(MathHelper.square(3)); // 输出: 9
console.log(MathHelper.cube(3)); // 输出: 27
解释:
MathHelper
类定义了两个静态方法 square
和 cube
,分别用于计算一个数的平方和立方。MathHelper
调用。class Example {
static staticProperty = "I am a static property";
instanceProperty = "I am an instance property";
}
console.log(Example.staticProperty); // 输出: "I am a static property"
const example1 = new Example();
const example2 = new Example();
console.log(example1.instanceProperty); // 输出: "I am an instance property"
console.log(example2.instanceProperty); // 输出: "I am an instance property"
// 错误: 静态属性不能通过实例访问
// console.log(example1.staticProperty);
解释:
staticProperty
是一个静态属性,可以通过类名 Example
直接访问。instanceProperty
是实例属性,每个 Example
实例都有自己独立的一份。static
关键字用于定义属于类本身的属性和方法,而不是类的实例。