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:

How to create static functions which can be called without an instance, and how do I assign static constants which 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