The static keyword defines a static method for a class.
Syntax
static methodName() { ... }
Description
Static methods are called without instantiating their class and are also not callable when the class is instantiated. Static methods are often used to create utility functions for an application.
Calling static method
From another static method
In order to call another static method in static method you can simply use this keyword.
class StaticMethodCall { static staticMethod() { return 'Static method have been called'; } static anotherStaticMethod() { return this.staticMethod() + ' from another static method'; } } StaticMethodCall.staticMethod(); // 'Static method have been called' StaticMethodCall.anotherStaticMethod(); // 'Static method have been called from another static method'
From class constructor and other methods
As static method is part of class, it's not accessible through this keyword. the solution to the problem would be using of CLASSNAME.STATIC_METHOD_NAME
(like other calls from outside of class) or this.constructor.STATIC_METHOD_NAME
.
class StaticMethodCall{ constructor(){ console.log(StaticMethodCall.staticMethod()); // 'static method have been called' console.log(this.constructor.staticMethod()); // 'static method have been called' } static staticMethod(){ return 'static method test have been called.'; } }
Examples
The following example demonstrates several things. It shows how a static method is implemented on a class and that a class with a static member can be subclassed. Finally it shows how a static method can and cannot be called.
class Triple { static triple(n) { n = n || 1; //should not be a bitwise operation 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 console.log(BiggerTriple.triple(3)); // 81 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'.
Specifications
Specification | Status | Comment |
---|---|---|
{{SpecName('ES6', '#sec-class-definitions', 'Class definitions')}} | {{Spec2('ES6')}} | Initial definition. |
{{SpecName('ESDraft', '#sec-class-definitions', 'Class definitions')}} | {{Spec2('ESDraft')}} |
Browser compatibility
{{CompatibilityTable}}
Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|
Basic support | {{CompatChrome(42.0)}} | {{CompatGeckoDesktop(45)}} | {{CompatUnknown}} | {{CompatUnknown}} | {{CompatUnknown}} |
Feature | Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile | Chrome for Android |
---|---|---|---|---|---|---|
Basic support | {{CompatNo}} | {{CompatGeckoMobile(45)}} | {{CompatUnknown}} | {{CompatUnknown}} | {{CompatUnknown}} | {{CompatChrome(42.0)}} |