In JavaScript, a class serves as a template for creating objects. Classes define properties and methods that objects (instances) created from this class will have. JavaScript supports classes since ECMAScript 2015 (ES6), which simplifies the definition of complex objects compared to earlier versions where functions were used to define classes.
class Car {
constructor(brand, model) {
this.brand = brand;
this.model = model;
}
displayInfo() {
console.log(`Car: ${this.brand} ${this.model}`);
}
}
let myCar = new Car("Toyota", "Corolla");
myCar.displayInfo(); // Outputs: Car: Toyota Corolla
Inheritance
Inheritance allows a class to inherit properties and methods from another class. In JavaScript, the extends
keyword is used for inheritance. This is very useful for reducing code redundancy and increasing its reusability.
class ElectricCar extends Car {
constructor(brand, model, range) {
super(brand, model);
this.range = range;
}
displayRange() {
console.log(`Range: ${this.range} km`);
}
}
let myElectricCar = new ElectricCar("Tesla", "Model S", 600);
myElectricCar.displayInfo(); // Outputs: Car: Tesla Model S
myElectricCar.displayRange(); // Outputs: Range: 600 km
Encapsulation
Encapsulation is an OOP principle that restricts direct access to certain components of an object and protects them from external access. In JavaScript, encapsulation is typically achieved using closures or newer language features such as class fields with the #
modifier, indicating private properties.
class BankAccount {
#balance;
constructor(balance) {
this.#balance = balance;
}
getBalance() {
return this.#balance;
}
deposit(amount) {
this.#balance += amount;
}
withdraw(amount) {
if (amount <= this.#balance) {
this.#balance -= amount;
} else {
console.log("Insufficient balance.");
}
}
}
Polymorphism
Polymorphism allows objects of different classes, inheriting from the same parent class, to respond to the same message/method in different ways. In JavaScript, polymorphism is often used together with inheritance.
class Animal {
makeSound() {
console.log("Animal makes a sound");
}
}
class Dog extends Animal {
makeSound() {
console.log("Dog barks");
}
}
class Cat extends Animal {
makeSound() {
console.log("Cat meows");
}
}
let animal = new Animal();
let dog = new Dog();
let cat = new Cat();
animal.makeSound();
dog.makeSound();
cat.makeSound();
In conclusion, OOP principles such as classes, inheritance, encapsulation, and polymorphism find wide application in the world of JavaScript. By using these principles, we can create modular, easily extensible, and maintainable code, which is crucial for developing complex applications.