Static method calls are made directly on the class and are not callable on instances of the class
Static methods are prepended with the static
keyword
class Car {
constructor(make, model, price) {
this._make = make
this._model = model
this._price = price
}
// instance methods
get price() {
return this._price
}
drive() {
console.log('calling "this" in an instance method', this)
console.log(`driving ${this._make} ${this._model}`)
}
// static method
static mostExpensiveCar(cars) {
console.log('calling "this" in a static method', this)
return cars.sort((a, b) => b.price - a.price)[0]
}
}
// Create 3 instances of the Car class
const car1 = new Car("honda", "accord", 20000)
const car2 = new Car("aston martin", "db7", 110000)
const car3 = new Car("bmw", "5 series", 50000)
// call static method mostExpensiveCar() on the Class (Car)
// not the instance
const priceyCar = Car.mostExpensiveCar([car1, car2, car3])
console.log(priceyCar)