TypeScript:static静态方法 作者:马育民 • 2025-10-12 21:23 • 阅读:10002 # 介绍 **静态方法**是使用 `static` 关键字修饰的 **方法(类中)** **注意:**不能修饰函数,否则报错 ### 概念 | 概念 | 说明 | | :--- | :--- | | **所属** | 属于 **类 (Class)**,而不是实例 (Instance)。 | | **访问方式** | 通过 **类名** 直接调用:`ClassName.methodName()`。 | | **创建时机** | 在类定义时就存在,不需要创建实例。 | | **共享性** | 所有该类的实例都**共享**同一个静态方法。 | | **`this` 指向** | 在静态方法内部,`this` 指向的是**类本身**,而不是实例。 | ### 应用场景 - 不需要访问属性的方法,可以定义成静态方法,如工具方法 # 例子 定义数学工具类 `MathUtils`,类中可以定义工具方法: - add() 加法 - area() 圆面积 ### 类 ```typescript class MathUtils { // ✅ 静态常量属性 static readonly PI: number = 3.14159; // ✅ 静态方法 static add(a: number, b: number): number { return a + b; } // 静态方法可以调用其他静态成员 static area(r: number): number { return MathUtils.PI * r * r; // ✅ 通过类名访问静态属性 } } ``` ### 调用静态方法 可通过 `类名 . 静态方法名` 调用,不像实例方法那样,需要先创建对象: ``` // 🔹 调用静态方法:使用 类名.方法名 console.log(MathUtils.add(2, 3)); // 输出: 5 console.log(MathUtils.area(3)); // 输出: 28.27431 ``` ### 不能通过 实例 调用静态方法 ``` const utils = new MathUtils(); utils.add(1, 2); // 编译错误! ``` ### 不能在静态方法中访问实例属性 ``` class Student { name: string = ""; static test(): void { // ❌ 错误!不能访问 this 或实例属性 console.log(this.name); // ❌ 实例属性不属于类 console.log(Student.name); } } ``` # 静态方法可以被子类继承 ```typescript class Parent { static hello() { console.log("Hello"); } } class Child extends Parent { } Child.hello(); // "Hello" ``` # 访问修饰符 静态方法也可以是 `private`、`protected` ```typescript class Secret { private static secretMethod() { /* ... */ } // 只能在类内部调用 } ``` # 静态方法 vs 实例方法 | 特性 | 静态方法 (`static`) | 实例方法 (普通方法) | | :--- | :--- | :--- | | **关键字** | `static` | 无 | | **所属** | 类本身 | 类的每个实例 | | **调用方式** | `ClassName.method()` | `instance.method()` | | **内存** | 只有一份 | 每个实例都有一份(但通常共享方法定义) | | **能否访问 `this`** | ✅ `this` 指向类本身 | ✅ `this` 指向当前实例 | | **能否访问实例成员** | ❌ 不能 | ✅ 能 | | **能否访问静态成员** | ✅ 能 | ✅ 能 | ### 对比示例 ```typescript class Counter { count: number = 0; // 实例属性 static totalInstances: number = 0; // 静态属性 constructor() { Counter.totalInstances++; // 静态方法可以访问静态属性 } // 实例方法 increment(): void { this.count++; // 可以访问实例属性 console.log(`Instance count: ${this.count}`); } // 静态方法 static getTotalInstances(): number { return Counter.totalInstances; // ❌ 不能写 `this.count` 或 `this.increment()` } } const c1 = new Counter(); const c2 = new Counter(); c1.increment(); // 实例方法调用 c2.increment(); console.log(Counter.getTotalInstances()); // 静态方法调用,输出: 2 ``` ## 总结 * `static` 方法属于**类本身**,不属于实例。 * 通过 **`ClassName.method()`** 调用。 * 不能访问实例成员,但可以访问静态成员。 * 常用于**工具函数、工厂方法、单例、常量**等场景。 * 是编写可复用、模块化代码的重要工具。 原文出处:http://malaoshi.top/show_1GW21uMrRQUt.html