JavaScript static methods belong to the class, not to the instance of the class. So JavaScript static methods are not called on the instance of the class they are made to call directly on the class.
JavaScript calls a static method from an instance
Simple example code calling the static method with the class name not creating the instance of the class. Using class name as an instance only.
<!DOCTYPE html>
<html>
<body>
<script>
class Syntax
{
static displayMessage()
{
return "static method called"
}
}
console.log(Syntax.displayMessage());
// creating instance
var s = new Syntax();
console.log(s.displayMessage); // Error
</script>
</body>
</html>
Output:
How to access static members on the instance?
Answer: You can try to get access to the static property via the constructor.
function Foo() {
this.publicProperty = "This is public property";
Object.getPrototypeOf(this).count++;
}
Foo.prototype.count = 0;
console.log(new Foo().count, new Foo().count, Foo.prototype.count);
Output: 1 2 2
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