类(class)通过 static 关键字定义静态方法。不能在类的实例上调用静态方法,而应该通过类本身调用。这些通常是实用程序方法,例如创建或克隆对象的功能。
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
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 = 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 不是一个函数'.
Specification | Status | Comment |
---|---|---|
ECMAScript 2015 (6th Edition, ECMA-262) Class definitions |
Standard | Initial definition. |
ECMAScript Latest Draft (ECMA-262) Class definitions |
Draft |
Desktop | Mobile | Server | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
static | Chrome
Full support
49
| Edge Full support 13 | Firefox Full support 45 | IE No support No | Opera Full support 36 | Safari Full support 9 | WebView Android ? | Chrome Android Full support Yes | Edge Mobile Full support 13 | Firefox Android Full support 45 | Opera Android ? | Safari iOS Full support 9 | Samsung Internet Android Full support Yes | nodejs
Full support
6.0.0
|