Object-Oriented Programming (OOP) in JavaScript
1. Objects and Classes
In JavaScript, objects are collections of key-value pairs (properties and methods). Classes serve as blueprints to create objects.
Example:
// Define a class
class Person {
constructor(name, age) {
this.name = name; // Property
this.age = age;
}
greet() { // Method
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
}
// Create an object
const person1 = new Person('Alice', 25);
person1.greet(); // Output: Hello, my name is Alice and I am 25 years old.
2. Encapsulation
Encapsulation means bundling data (properties) and methods that manipulate the data inside a single unit (object). It restricts direct access to certain parts of an object.
Example:
class BankAccount {
#balance; // Private field
constructor(initialBalance) {
this.#balance = initialBalance;
}
deposit(amount) {
this.#balance += amount;
}
getBalance() {
return this.#balance;
}
}
const account = new BankAccount(1000);
account.deposit(500);
console.log(account.getBalance()); // 1500
// console.log(account.#balance); // Error: Private field '#balance' not accessible
3. Inheritance
Inheritance allows a class to inherit properties and methods from another class. It helps reuse existing code.
Example:
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise.`);
}
}
class Dog extends Animal {
speak() {
console.log(`${this.name} barks.`);
}
}
const dog = new Dog('Buddy');
dog.speak(); // Output: Buddy barks.
4. Polymorphism
Polymorphism means having multiple forms. In OOP, it allows methods in child classes to have the same name as methods in the parent class but behave differently.
Example:
class Shape {
area() {
return 0;
}
}
class Rectangle extends Shape {
constructor(width, height) {
super();
this.width = width;
this.height = height;
}
area() {
return this.width * this.height;
}
}
const shape = new Shape();
const rectangle = new Rectangle(10, 5);
console.log(shape.area()); // 0
console.log(rectangle.area()); // 50
5. Abstraction
Abstraction hides the complexity of the code and only shows the essential parts to the user.
Example:
class Vehicle {
startEngine() {
console.log('Engine started');
}
}
class Car extends Vehicle {
drive() {
console.log('Driving the car...');
}
}
const car = new Car();
car.startEngine(); // Engine started
car.drive(); // Driving the car...
6. Static Methods and Properties
Static methods and properties belong to the class itself, not to the instances.
Example:
class MathUtils {
static add(a, b) {
return a + b;
}
}
console.log(MathUtils.add(5, 3)); // 8
7. Prototypes
JavaScript uses a prototype-based inheritance model, where objects can inherit properties and methods from other objects.
Example:
function Person(name) {
this.name = name;
}
Person.prototype.greet = function() {
console.log(`Hello, my name is ${this.name}`);
};
const person = new Person('Alice');
person.greet(); // Hello, my name is Alice
Key Takeaways
- Use classes to create blueprints for objects.
- Encapsulate properties with private fields using
#
. - Use inheritance (
extends
) to reuse code. - Override methods for polymorphism.
- Simplify interactions with abstraction.
- Leverage static methods and prototype inheritance.
JavaScript’s OOP features allow developers to write clean, modular, and reusable code.
Hi, I'm Abhay Singh Kathayat!
I am a full-stack developer with expertise in both front-end and back-end technologies. I work with a variety of programming languages and frameworks to build efficient, scalable, and user-friendly applications.
Feel free to reach out to me at my business email: kaashshorts28@gmail.com.
Top comments (0)