静态方法中的this指向调用它的类本身而非实例,支持子类多态;不能访问实例属性或方法,且不可用箭头函数声明、不可通过实例调用。

比如:
class User {
static getName() {
console.log(this === User); // true
return this.name;
}
}
User.name = 'UserClass';
console.log(User.getName()); // 'UserClass'
这里 `this` 就是 `User`,所以能读取 `User.name`,也能调用其他静态方法(如 `this.create()`)。
为什么不能访问实例属性?
因为静态方法运行时根本没创建实例,`this` 不是某个 `new User()` 出来的对象,自然没有 `this.name` 或 `this.sayHello()` 这类实例成员。
- 试图读 `this.name` → 得到 `undefined`(除非类上显式定义了静态 `name`)
- 试图调 `this.sayHello()` → 报错 `is not a function`(除非 `sayHello` 是静态方法)
子类调用时 this 指向谁?
指向**实际调用它的类**,不是定义它的父类。
- 如果 `Admin extends User`,然后 `Admin.getName()`,那 `this` 就是 `Admin`
- 这使得 `this` 在静态方法中支持多态:`this.create()` 会调用 `Admin.create()` 而不是 `User.create()`
和普通工具函数的区别在哪?
静态方法的 `this` 具备动态绑定能力,而普通函数没有。
- 写成 `function getName() { return this.name; }`,单独调用时 `this` 指向全局或 `undefined`(严格模式)
- 但 `static getName() { return this.name; }` 中的 `this` 始终可靠指向当前类,无需手动 bind 或传参
常见误操作提醒
- 不能用箭头函数声明静态方法:`static foo = () => {}` 语法错误
- 不能在静态方法里用 `super()`,要用 `super.staticMethod()`
- 不能通过实例调用:`new User().getName()` 会报错,必须 `User.getName()`











