Static class methods are defined on the class itself, not on instances of the class.
Therefore, you can only call a static method on the class, not on an object instance.
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. |
To use the myCar object inside a static method, you can pass it as a parameter.
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); |