What is role of static method in JS?

0 votes
27 views
Ravi Vishwakarma asked 10 days ago in Web Application by Ravi Vishwakarma

What is role of static method in JS?    

1 Answer

0 votes
Ethan Karla answered 7 days ago by Ethan Karla
By definition, static methods are associated with a class, not the instances of that class. Thus, static methods are useful for defining helper or utility methods.
Syntax: 

class class-name{
 constructor(){
  //statement
 }
 static method-name( [arguments] ){
  //statement
 }
}
Example

class Person {
 constructor(name) {
  this.name = name;
 }
 getName() {
  return this.name;
 }
 static createAnonymous(gender) {
  let name = gender == 'male' ? 'John Doe' : 'Jane Doe';
  return new Person(name);
 }
}
let anonymous = Person.createAnonymous('male');
If you attempt to call the static method from an instance of the class, you’ll get an error. For example.
• JavaScript static methods are shared among instances of a class. Thus, they are associated with the class, not any particular instance of that class.
• The static methods are called via the class name, not the instances of the class.
• Use the className.staticMethodName() or this.constructor.staticMethodName() to call a static method in a class constructor or an instance method.