JavaScript Object-Oriented Programming (OOP) with Examples
Object-Oriented Programming (OOP) is a programming paradigm based on the concept of "objects", which can contain data and code. In JavaScript, OOP allows for the creation of objects that represent real-world entities, facilitating code reuse and modularity.
1. Understanding Objects
In JavaScript, an object is a standalone entity with properties and type. Objects can hold data (properties) and functions (methods).
// Creating an object
const car = {
make: 'Toyota',
model: 'Camry',
year: 2020,
displayInfo: function() {
return `${this.year} ${this.make} ${this.model}`;
}
};
console.log(car.displayInfo()); // Output: 2020 Toyota Camry2. Classes and Constructors
Classes are a template for creating objects. You can define a class and use a constructor to initialize properties.
// Defining a class
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
introduce() {
return `Hello, my name is ${this.name} and I am ${this.age} years old.`;
}
}
// Creating an instance of the class
const person1 = new Person('Alice', 30);
console.log(person1.introduce()); // Output: Hello, my name is Alice and I am 30 years old.3. Inheritance
Inheritance allows one class to inherit the properties and methods of another class. This promotes code reuse.
// Base class
class Animal {
constructor(name) {
this.name = name;
}
speak() {
return `${this.name} makes a noise.`;
}
}
// Derived class
class Dog extends Animal {
speak() {
return `${this.name} barks.`;
}
}
const dog = new Dog('Buddy');
console.log(dog.speak()); // Output: Buddy barks.4. Encapsulation
Encapsulation is the bundling of data with the methods that operate on that data. It restricts direct access to some of the object’s components.
class BankAccount {
constructor(balance) {
this._balance = balance; // Private property
}
deposit(amount) {
this._balance += amount;
}
withdraw(amount) {
if (amount <= this._balance) {
this._balance -= amount;
} else {
console.log('Insufficient funds');
}
}
getBalance() {
return this._balance;
}
}
const account = new BankAccount(1000);
account.deposit(500);
account.withdraw(200);
console.log(account.getBalance()); // Output: 13005. Polymorphism
Polymorphism allows methods to do different things based on the object it is acting upon, often achieved through method overriding.
class Cat extends Animal {
speak() {
return `${this.name} meows.`;
}
}
const cat = new Cat('Whiskers');
console.log(cat.speak()); // Output: Whiskers meows.
console.log(dog.speak()); // Output: Buddy barks.Conclusion
JavaScript OOP allows developers to create reusable and modular code. Understanding objects, classes, inheritance, encapsulation, and polymorphism is essential for effective programming in JavaScript.
You need to be logged in to participate in this discussion.