Loading

Static Method

  • In JavaScript, a static method is a method that is associated with a class itself, rather than with instances of the class.
  • Static methods are defined on the class's constructor function and cannot be called on instances of the class.
  • They are primarily used for utility functions or operations that are not specific to individual instances but are related to the class as a whole.

Syntax:

class MyClass {
 // Instance properties and constructor (if needed) go here
 // Define a static method
 static myStaticMethod() {
   // Code for the static method goes here
 }
}
// To call the static method, you don't need an instance
MyClass.myStaticMethod();

Example:

<!DOCTYPE html>
<html>
<body>
  <script>
    class Test {
      static display() {
        return "static method is invoked"
      }
    }
    document.writeln(Test.display());
  </script>

</body>

</html>

Output:

static method is invoked


Example:

<!DOCTYPE html>
<html>

<body>

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

</body>

</html>

Output:

static method is invoked

static method is invoked again