Mastering JavaScript Classes With an Example
A comprehensive guide for those who want to learn all about JavaScript classes
Published in
4 min readMar 7, 2023
Object-Oriented Programming (OOP) is a programming paradigm that allows developers to model real-world objects as software entities. JavaScript is a versatile programming language that supports OOP concepts, including classes, encapsulation, inheritance, and polymorphism.
In today’s article, we will examine all class properties and how their methods are implemented with a detailed example.
Let’s create a Vehicle
class that will be inherited by various vehicle types such as Car
, Motorcycle
, and Truck
.
class Vehicle {
#color // private class field property
_sunroof = false // protected class field property
constructor(model, year, color) {
this.model = model // public property
this.year = year // public property
this.#color = color // private property
this._isEngineOn = false // protected property
}
// Private method
#startEngine() {
console.log(`Engine is started`)
this._isEngineOn = true
}
// Private method
#stopEngine() {
console.log(`Engine is stopped`)
this._isEngineOn = false
}
// Public method
turnOn() {
this.#startEngine()
}
// Public method
turnOff() {
this.#stopEngine()
}
// Static method
static honk() {…