I have a class with a static method:
class User { constructor() { User.staticMethod(); } static staticMethod() {} }
Is there an equivalent to this for static methods (i.e. refer to the current class without an instance)?
this.staticMethod()
So I don't have to write the class name: "User".
In order to call a static method from another static method, we can use 'this' keyword. 2) this. constructor. static_method_name(); : Or by using the constructor property.
A static method can be called directly from the class, without having to create an instance of the class. A static method can only access static variables; it cannot access instance variables. Since the static method refers to the class, the syntax to call or refer to a static method is: class name. method name.
The JavaScript allows static methods that belong to the class rather than an instance of that class. Hence, an instance is not needed to call such static methods. Static methods are called on the class directly.
A static method in JavaScript is a method that has a static keyword prepended to itself. Such methods cannot be accessed through instantiated objects but could be accessed through the class name. This is because static methods belong to the class directly. Inheritance even applies to static methods.
From MDN documentation
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.
For more please see=> https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static
You can do something like this => this.constructor.staticMethod());
to call static method.
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.'; } }
Instead of: User.staticMethod()
you can use: this.constructor.staticMethod()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With