JavaScript Static Methods
Class methods that don't change often are set on the class directly.
You can't use astatic
method on an instance; it can only be used on the class of the object.
If you wish to utilize the myCar object within the static
method, you can pass it as a parameter:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Class Static Methods</h1>
<p>A static method is made using the word "static". You can only use this method directly on the class itself.</p>
<p id="demo"></p>
<script>
class Car {
constructor(name) {
this.name = name;
}
static hello() {
return "Hello!!";
}
}
const 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>
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Class Static Methods</h1>
<p>To use the "myCar" object in the static method, you can pass it as a parameter.</p>
<p id="demo"></p>
<script>
class Car {
constructor(name) {
this.name = name;
}
static hello(x) {
return "Hello " + x.name;
}
}
const myCar = new Car("Ford");
document.getElementById("demo").innerHTML = Car.hello(myCar);
</script>
</body>
</html>