Home >>Javascript Tutorial >JavaScript static Method

JavaScript static Method

JavaScript Static Method

The JavaScript delivers static methods that belongs to a class instead of an instance of that same class. Hence, an instance is not necessary to call the static method. Point to be noted is that these methods are called directly on the class.

Please note that these following points should be kept in mind:

  • To declare a static method, static keyword is used.
  • The static method can have any name.
  • There can be more than one static method in a class.
  • Whenever more than one static method with a similar name is declared, the JavaScript always invokes the last one.
  • In order to create utility functions static methods can be used.
  • This keyword can be used to call a static method within another static method.
  • Please note that we cannot use this keyword directly to call a static method within the non-static method. If such cases occurs then static method can be called either using the class name or as the property of the constructor.

JavaScript Static Method Examples

1. Here is an example of simple static method:

<script>
class Test
{
  static display()
  {
    return "static method is great"
  }
}
document.writeln(Test.display());
</script>
Output :static method is great

2. Here is example depicting the invoking of more than one static method:

<script>
class Test
{
  static display1()
  {
    return "static method is used"
  }
  static display2()
  {
    return "static method is used again"
  }
}
document.writeln(Test.display1()+"<br>");
document.writeln(Test.display2());
</script>
Output :
static method is used
static method is used again

3. Here is an example to invoke more than one static method with similar names.

<script>
class Test
{
  static display()
  {
    return "static method is used"
  }
  static display()
  {
    return "static method is used again"
  }
}
document.writeln(Test.display());
</script>
Output :
static method is used again

4. Here is an example to invoke a static method within the constructor.

<script>
class Test {
  constructor() {
  document.writeln(Test.display()+"<br>"); 
  document.writeln(this.constructor.display()); 
  }

  static display() {
      return "static method is used"
  }
}
var t=new Test();
</script>
Output :
static method is used
static method is used

5. Here is an example to invoke a static method within the non-static method.

<script>
class Test {
  static display() {
      return "static method is used"
  }
  
 show() {
  document.writeln(Test.display()+"<br>"); 
  }  
}
var t=new Test();
t.show();
</script>
Output :
static method is used

No Sidebar ads