The static
keyword defines a static method for a class. Static methods aren't called on instances of the class. Instead, they're called on the class itself. These are often utility functions, such as functions to create or clone objects.
static methodName() { ... }
Static method calls are made directly on the class and are not callable on instances of the class. Static methods are often used to create utility functions.
In order to call a static method within another static method of the same class, you can use the this
keyword.
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'
Static methods are not directly accessible using the this
keyword from non-static methods. You need to call them using the class name: CLASSNAME.STATIC_METHOD_NAME()
or by calling the method as a property of the constructor
: 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.'; } }
The following example demonstrates several things:
class Triple { static triple(n) { if (n === undefined) { n = 1; } return n * 3; } } class BiggerTriple extends Triple { static triple(n) { return super.triple(n) * super.triple(n); } } console.log(Triple.triple()); // 3 console.log(Triple.triple(6)); // 18 var tp = new Triple(); console.log(BiggerTriple.triple(3)); // 81 (not affected by parent's instantiation) console.log(tp.triple()); // 'tp.triple is not a function'.
Specification | Status | Comment |
---|---|---|
ECMAScript 2015 (6th Edition, ECMA-262) The definition of 'Class definitions' in that specification. | Standard | Initial definition. |
ECMAScript Latest Draft (ECMA-262) The definition of 'Class definitions' in that specification. | Draft |
Desktop | ||||||
---|---|---|---|---|---|---|
Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | |
Basic support | 49
|
13 | 45 | No | 36 | 9 |
Mobile | |||||||
---|---|---|---|---|---|---|---|
Android webview | Chrome for Android | Edge Mobile | Firefox for Android | Opera for Android | iOS Safari | Samsung Internet | |
Basic support | ? | Yes | 13 | 45 | ? | 9 | Yes |
Server | |
---|---|
Node.js | |
Basic support | 6.0.0
|
© 2005–2018 Mozilla Developer Network and individual contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static