Skip to content

JavaScript static function inside class | Example code

  • by

To declare a JavaScript static function inside a class, simply prefix a function declaration with the static keyword inside the class declaration. The static function does not need class instances, it will call directly with the class name.

Post ES6 we can define a static function in a class as follows:

class MyClass {
    static someMethod () {
        console.log('Doing someMethod');
    }
}

Pre ES6 I can create a base class as follows:

var MyClassBase = function(str){
    this.m_Data = str; // This acts a bit like a constructor where you can assign data within the class
};

JavaScript static function inside a class

Simple example code static class methods are defined on the class itself.

<!DOCTYPE html>
<html>
<body>
  <script>    
   class Car {
    
    constructor(name) {
      this.name = name;
    }

    static msg() {
      return "Hello!!";
    }
  }

  let myCar = new Car("BMW");

  // call 'msg()' on the Car Class:
  console.log(Car.msg());

  // calling with Car Object:
  console.log(myCar.hello()); // error

</script>  

</body>
</html>

Output:

JavaScript static function inside class

Or you can define static functions inside a class using the static keyword. Static functions are associated with the class itself rather than instances of the class. They are called on the class itself, not on instances of the class. Here’s an example:

class MyClass {
  // Instance method
  myInstanceMethod() {
    console.log('This is an instance method');
  }

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

// Creating an instance of the class
const myObject = new MyClass();

// Calling the instance method
myObject.myInstanceMethod(); // Output: This is an instance method

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

In the example above, myInstanceMethod is an instance method, and myStaticMethod is a static method. When you create an instance of MyClass (e.g., myObject), you can call the instance method on that instance. However, the static method is called directly on the class itself, not on an instance.

How to create static functions that can be called without an instance, and how do I assign static constants that can be accessed without an instance?

Answer: Both methods and constants are just properties of the class (constructor function) object, and are created by assignment:

var MyClassBase = function(str){
    this.m_Data = str;
};
MyClassBase.STATIC_STRING = "Ooops";

Source: stackoverflow.com

Do comment if you have any doubts or suggestions on this Js static 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

Your email address will not be published. Required fields are marked *