JavaScript Static Methods
- Previous Page JS Class Inheritance
- Next Page JS Callback
Static class methods are defined on the class itself.
You cannot call on an object static
Methods can only be called on object classes.
Instance
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 you cannot call it on the Car object: // document.getElementById("demo").innerHTML = myCar.hello(); // This will cause an error.
If you want to static
You can use the myCar object in methods and pass it as a parameter:
Instance
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);
- Previous Page JS Class Inheritance
- Next Page JS Callback