ref – https://medium.com/@yyang0903/static-objects-static-methods-in-es6-1c026dbb8bb1
Static methods, like many other features introduced in ES6, are meant to provide class-specific methods for object-oriented programming in Javascript.
Static methods are often used to create utility functions for an application.
Static methods are called without instantiating their class…
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
class Triple { constructor() { console.log("constructing Triple class..."); } static triple(n) { if (n === undefined) { n = 1; } return n * 3; } } // Static methods are often used to create utility functions for an application. console.log(Triple.triple()); // 3 console.log(Triple.triple(6)); // 18 |
thus, when we call static “triple”, you will won’t see the log in the constructor executed.
Static methods…are also not callable when the class is instantiated.
1 2 |
var tp = new Triple(); console.log(tp.triple(3)); // ERROR - tp.triple is not a function |
Since these methods operate on the class instead of instances of the class, they are called on the class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
class StaticMethodCall { // Static methods are not directly accessible using the // this keyword (or standalone call) from non-static methods. // You need to call them using the class name constructor() { // instance method // correct ways console.log(StaticMethodCall.staticMethod()); console.log(StaticMethodCall.anotherStaticMethod()); } hadoken() { // instance method // incorrect ways // console.log(staticMethod()); // "staticMethod" not defined // console.log(this.staticMethod()); // this.staticMethod is not a function console.log(StaticMethodCall.staticMethod()); // OK } // You can call a static method from another static method within the same class with this. static anotherStaticMethod() { return "anotherStaticMethod - " + this.staticMethod(); } // static method static staticMethod() { return "staticMethod - " + 'static method has been called.'; } } let p = new StaticMethodCall(); p.hadoken(); |
Say we have a subclass to a parent class, any static methods that we declared are available to the subclasses as well
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
class Triple { constructor() { console.log("constructing Triple class..."); } static triple(n) { if (n === undefined) { n = 1; } return n * 3; } } class BiggerTriple extends Triple { constructor() { console.log("constructing BiggerTriple class..."); } static triple(n) { return super.triple(n) * super.triple(n); } } console.log(BiggerTriple.triple(3)); // 81 |