static 关键字为一个类定义了一个静态方法。
语法
static methodName() { ... }
描述
静态方法调用直接在类上进行,而在类的实例上不可被调用。
静态方法通常用于创建 实用/工具 函数。
调用静态方法
从另一个静态方法
为了在同一个类的另一个静态方法中调用一个静态方法,你可以使用 this 关键字。
class StaticMethodCall {
static staticMethod() {
return 'Static method has been called';
}
static anotherStaticMethod() {
return this.staticMethod() + ' from another static method';
}
}
StaticMethodCall.staticMethod();
// 'Static method has been called'
StaticMethodCall.anotherStaticMethod();
// 'Static method has been called from another static method'
从类的构造函数和其他方法
静态方法不能直接在非静态方法中使用 this 关键字来访问。你需要使用类名来调用它们:CLASSNAME.STATIC_METHOD_NAME() 或者将其作为构造函数的属性来调用该方法: this.constructor.STATIC_METHOD_NAME().
class StaticMethodCall {
constructor() {
console.log(StaticMethodCall.staticMethod());
// 'static method has been called.'
console.log(this.constructor.staticMethod());
// 'static method has been called.'
}
static staticMethod() {
return 'static method has been called.';
}
}
示例
下面的例子说明了这几点:
- 一个静态方法在一个类上是如何被实现的。
- 具有一个静态成员的一个类是可以被子类化 。
- 一个静态方法如何能被调用和不能被调用。
class Tripple {
static tripple(n) {
n = n || 1;
return n * 3;
}
}
class BiggerTripple extends Tripple {
static tripple(n) {
return super.tripple(n) * super.tripple(n);
}
}
console.log(Tripple.tripple());
// 3
console.log(Tripple.tripple(6));
// 18
let tp = new Tripple();
console.log(BiggerTripple.tripple(3));
// 81(不会受父类实例化的影响)
console.log(tp.tripple());
// 'tp.tripple 不是一个函数'.
规范
| 规范 | 状态 | 说明 |
|---|---|---|
| ECMAScript 2015 (6th Edition, ECMA-262) Class definitions |
Standard | Initial definition. |
| ECMAScript Latest Draft (ECMA-262) Class definitions |
Living Standard |
浏览器兼容性
| Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
|---|---|---|---|---|---|
| Basic support | 42.0 | 45 (45) | ? | ? | ? |
| Feature | Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile | Chrome for Android |
|---|---|---|---|---|---|---|
| Basic support | 未实现 | 45.0 (45) | ? | ? | ? | 42.0 |