Static class methods are defined on the class itself. You cannot call a static method on an object instance, only on the class template. This makes them perfect for utility functions that don't depend on specific object data.
Use the static keyword to define a static method:
class Car {
constructor(name) {
this.name = name;
}
static hello() {
return "Hello!!";
}
}
let myCar = new Car("Ford");
Static methods be called on the Class, not on the instance:
// Correct:
console.log(Car.hello());
// Incorrect: This will throw an error
// console.log(myCar.hello());
this.name, etc.).new Class().class User {
constructor(name) {
this.name = name;
}
static compare(user1, user2) {
return user1.name === user2.name;
}
}
let u1 = new User("Mim");
let u2 = new User("Mim");
User.compare(u1, u2); // returns true
this. You must use the class name:
ClassName.staticMethod().
static keyword