JS Tutorial
JS Version
JS Objects
JS Function
JS Classes
JS Async
JS HTML DOM
JS Browser BOM
JS Web API
JS AJAX
JS JSON
JS vs JQUERY
JS Graphics
Class Static
Static class methods are defined by the class itself.
The static method cannot be called on an object, only on an object class.
Example
Create a class named “Model” which will inherit the methods from the “Car” class.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Class Static Methods</h2>
<p>A static method is created with the “static” keyword, and you can only call the method on the class itself.</p>
<p id=”demo”></p>
<script>
class Car {
constructor(name) {
this.name = name;
}
static hello() {
return “Hello!!”;
}
}
let myCar = new Car(“Ford”);
//You can call ‘hello()’ on the Car Class:
document.getElementById(“demo”).innerHTML = Car.hello();
// But NOT on a Car Object:
// document.getElementById(“demo”).innerHTML = myCar.hello();
// this will raise an error.
</script>
</body>
</html>
Output
JavaScript Class Static Methods
A static method is created with the "static" keyword, and you can only call the method on the class itself.
Hello!!
Use the myCar object inside the static method, you can send it as a parameter.
Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Class Static Methods</h2>
<p>To use the “myCar” object inside the static method, you can send it as parameter.</p>
<p id=”demo”></p>
<script>
class Car {
constructor(name) {
this.name = name;
}
static hello(x) {
return “Hello ” + x.name;
}
}
let myCar = new Car(“Ford”);
document.getElementById(“demo”).innerHTML = Car.hello(myCar);
</script>
</body>
</html>
Output
JavaScript Class Static Methods
To use the "myCar" object inside the static method, you can send it as parameter.
Hello Ford