Calling Static Methods from Non-Static ES6 Class Methods
When working with ES6 classes, you may encounter the need to access static methods from within non-static class methods. There are two primary options for achieving this: using the constructor or referring to the class name directly. While either method is technically viable, they exhibit different behaviors in the context of inheritance with overridden static methods.
Option 1: Using the Constructor
class SomeObject { constructor(n) { this.n = n; } static print(n) { console.log(n); } printN() { this.constructor.print(this.n); } }
In this example, the static method print is accessed via the constructor this.constructor. This approach ensures that the correct static method is invoked, even if the class is extended and the static method is overridden in the subclass.
Option 2: Referring to the Class Name Directly
class SomeObject { constructor(n) { this.n = n; } static print(n) { console.log(n); } printN() { SomeObject.print(this.n); } }
In this case, the static method print is referenced by its class name. This method is essentially static and always returns the original value defined in the class, regardless of any inheritance relationships.
Inheritance and Override Considerations
The choice between using the constructor or the class name directly becomes important when dealing with inheritance and overridden static methods, as illustrated below:
class Super { static whoami() { return "Super"; } lognameA() { console.log(Super.whoami()); } lognameB() { console.log(this.constructor.whoami()); } } class Sub extends Super { static whoami() { return "Sub"; } }
Case 1: Using Super.whoami()
Case 2: Using this.constructor.whoami()
The behavior in these scenarios may vary depending on whether the static method is actually overridden or not. Referencing the static property via the class name provides true static behavior, while using this.constructor allows for dynamic dispatch and inheritance considerations. Choosing the appropriate method depends on the desired behavior in the given context.
The above is the detailed content of How to Call Static Methods from Non-Static ES6 Class Methods?. For more information, please follow other related articles on the PHP Chinese website!