Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

js call static method from class

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".

like image 320
Chris Avatar asked Apr 25 '17 14:04

Chris


People also ask

How do you call a static method from a class in JavaScript?

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.

How do you call a static method?

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.

Are there static methods in JavaScript?

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.

What is static method in class in JavaScript?

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.


2 Answers

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.';   } } 
like image 125
Rohith K P Avatar answered Sep 21 '22 13:09

Rohith K P


Instead of: User.staticMethod() you can use: this.constructor.staticMethod()

like image 33
Santhosh Kumar Avatar answered Sep 22 '22 13:09

Santhosh Kumar