Skip to content

JavaScript Static Class Methods

  • by

JavaScript static class methods belong to a class rather than an instance of that class. You don’t need an instance to call the static method so, instead, you can invoke the methods on the class itself. We can say that static in JavaScript belongs to the class and not the class instance.

static methodName() { … }
static propertyName [= value];

A JavaScript static method is a utility function; for instance, it could be a function to clone or create objects. On the other hand, static properties are beneficial for fixed configurations, caches, or data that you do not want to be replicated across instances.

Calls the static function using className.functionName

className.functionName

JavaScript Static Class Methods

Simple example code defines static methods using the static keyword.

<!DOCTYPE html>
<html>
<body>

  <script>
    class ABC {

      // static keyword used function
      static example1() {
        return "static method 1"
      }
    }

    // Direct call
    console.log(ABC.example1())

    // Using isntance
    var abc= new ABC();
    console.log(abc.example1);

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

Output:

JavaScript Static Class Methods
class MyClass {
  // Instance method
  myMethod() {
    console.log("This is an instance method");
  }

  // Static method
  static myStaticMethod() {
    console.log("This is a static method");
  }
}

// Creating an instance of MyClass
const myInstance = new MyClass();

// Calling instance method
myInstance.myMethod(); // Output: This is an instance method

// Calling static method
MyClass.myStaticMethod(); // Output: This is a static method

In this example, myMethod is an instance method, meaning it’s accessible only through instances of the class MyClass. On the other hand, myStaticMethod is a static method, meaning you can call it directly on the class itself, without needing to create an instance.

Static methods are useful for utility functions or operations that don’t depend on the state of any particular instance of the class.

Do comment if you have any doubts or suggestions on this JS static method.

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