static method in JavaScript

The blog provides the usage of static variables and static method in JavaScript. The static keyword is used to create a static method or static variable which indicates that the static method or static variable cannot be called on the instance of the class. 

The static methods are often used as utility functions to create or clone objects.

The static variables are useful for caches, reading configurations or other related data which need to be shared across instances.

How Static methods are to be defined in JavaScript ?

The below given points need to be considered while creating static methods

  • The keyword “static” is to be used to create static methods
  • More than one static methods can be created in the class
  • If two static methods are created with same name, the last one will be invoked by JavaScript
  • The static methods are often used as utility functions to create or clone objects
  • The static method allows to invoke another static method by using “this” keyword
  • The non -static method cannot invoke static method by using “this” keyword
  • The static method can be invoked from the class constructor
JavaScript Static Method Example

The below given is the simple static method example

  1. Creates a static variable to store membership status
  2. Creates static method – getMembershipStatus() to get the membership status
  3. Creates another static method which internally calls static method – getMembershipStatus()
<script>  
class customerClass {
  static customerType = 'Gold Membership';
  static getMembershipStatus() {
    return 'Customer has ' + this.customerType + ' in the system';
  }
  static customerStatus() {
    return ' Customer Status :::' + this.getMembershipStatus() ;
  }
}
document.writeln(customerClass.getMembershipStatus() +"<br>");  
// invokes the static method to get customer membership status
document.writeln(customerClass.customerStatus() +"<br>");  
// static method calls the static method to get customer membership status
</script> 

Output :

Customer has Gold Membership in the system
Customer Status :::Customer has Gold Membership in the system
Static Method Example using class constructor
  1. Define the Class
  2. Create static method
  3. Invoke the static method from constructor
<script>  
class StaticMethodConsCall {
  constructor() {
	document.writeln(StaticMethodConsCall.invoke()+"<br>");   
	document.writeln(this.constructor.invoke());	
  }

  static invoke() {
    return 'This is static method call'
  }
}
var v = new StaticMethodConsCall();
</script>