Skip to content

JavaScript static method/function | Code

  • by

You can create a JavaScript static method that belongs to the class rather than an instance of that class. This means you can’t call a static method on an object.

Therefore, static methods are useful for defining helper or utility methods. In ES6, you define static methods using the static keyword.

class Test  
   {  
    static display()  
    {  
      //code
    }  
  } 

JavaScript static method

Simple example code.

<!DOCTYPE html>
<html>
<body>
  <script>

   class Test  
   {  
    static display()  
    {  
      console.log( "Static method is invoked")  
    }  
  }  
  Test.display();

  var T1 =  new Test();
  T1.display();

</script>
</body>
</html> 

Output:

JavaScript static method

Invoke more than one static method

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

Static class methods with parameters

use the myCar object inside the static method, you can send it as a parameter:

<script>

    class Car {
      constructor(name) {
        this.name = name;
      }
      static hello(x) {
        return "Hello!!" + x.name;;
      }
    }

    let myCar = new Car("BMW");

    console.log(Car.hello(myCar));
</script>

Output: Hello!!BMW

To define a static method in JavaScript, you use the static keyword within the class definition. Here’s an example of how you can define and use a static method:

class MyClass {
  constructor(value) {
    this.value = value;
  }

  // Instance method
  instanceMethod() {
    return this.value;
  }

  // Static method
  static staticMethod() {
    return 'This is a static method';
  }
}

// Creating an instance of the class
const myInstance = new MyClass('Hello, World');

// Calling the instance method on the instance
console.log(myInstance.instanceMethod()); // Output: Hello, World

// Calling the static method on the class itself
console.log(MyClass.staticMethod()); // Output: This is a static method

In the example above, staticMethod is a static method of the MyClass class, and you can call it directly on the class without creating an instance. On the other hand, instanceMethod is an instance method, and it can be called on instances of the class, like myInstance in the example. Static methods are often used for operations that are not tied to a specific instance’s state but are relevant to the class as a whole.

Do comment if you have any doubts or suggestions on this Js function topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading