Dular SharmaDular SharmaDular Sharma
(Monday - Saturday)
sharmadular7392@gmail.com
Himatnagar
Dular SharmaDular SharmaDular Sharma

Chapter 25. Object Oriented JavaScript

20 Views

Object-Oriented Programming (OOP) is a programming paradigm that uses “objects” to design and structure software. JavaScript, despite being primarily known as a prototype-based language, supports OOP principles and allows developers to create objects and leverage their capabilities. This blog will explore the basics of Object-Oriented JavaScript, including creating objects, defining classes, inheritance, and practical examples.

What is Object-Oriented Programming?

Object-Oriented Programming is a programming paradigm centered around objects. An object is a collection of related data (properties) and functions (methods) that represents a real-world entity.

Creating Objects in JavaScript

Object Literals

The simplest way to create an object in JavaScript is by using object literals.

let person = {
    name: 'John Doe',
    age: 30,
    greet: function() {
        console.log('Hello, my name is ' + this.name);
    }
};

person.greet(); // Output: Hello, my name is John Doe

In this example, the person object has properties name and age, and a method greet.

Constructor Functions

Constructor functions are used to create multiple instances of objects with similar properties and methods.

function Person(name, age) {
    this.name = name;
    this.age = age;
    this.greet = function() {
        console.log('Hello, my name is ' + this.name);
    };
}

let person1 = new Person('John Doe', 30);
let person2 = new Person('Jane Doe', 25);

person1.greet(); // Output: Hello, my name is John Doe
person2.greet(); // Output: Hello, my name is Jane Doe

In this example, the Person constructor function allows the creation of multiple person objects with different names and ages.

Defining Classes

ES6 introduced the class syntax, making it easier to define and work with classes in JavaScript.

class Person {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }

    greet() {
        console.log('Hello, my name is ' + this.name);
    }
}

let person1 = new Person('John Doe', 30);
let person2 = new Person('Jane Doe', 25);

person1.greet(); // Output: Hello, my name is John Doe
person2.greet(); // Output: Hello, my name is Jane Doe

In this example, the Person class defines a constructor and a greet method. Instances of the Person class can be created using the new keyword.

Inheritance

Inheritance allows one class to inherit properties and methods from another class, promoting code reuse and modularity.

class Animal {
    constructor(name) {
        this.name = name;
    }

    speak() {
        console.log(this.name + ' makes a noise.');
    }
}

class Dog extends Animal {
    constructor(name, breed) {
        super(name);
        this.breed = breed;
    }

    speak() {
        console.log(this.name + ' barks.');
    }
}

let dog = new Dog('Rex', 'German Shepherd');
dog.speak(); // Output: Rex barks.

In this example, the Dog class extends the Animal class and overrides the speak method to provide specific behavior for dogs.

Encapsulation

Encapsulation is the bundling of data and methods that operate on that data within a single unit (class), and restricting access to some of the object’s components.

class BankAccount {
    #balance;

    constructor(balance) {
        this.#balance = balance;
    }

    deposit(amount) {
        this.#balance += amount;
    }

    withdraw(amount) {
        if (amount <= this.#balance) {
            this.#balance -= amount;
        } else {
            console.log('Insufficient funds');
        }
    }

    getBalance() {
        return this.#balance;
    }
}

let account = new BankAccount(1000);
account.deposit(500);
account.withdraw(300);
console.log(account.getBalance()); // Output: 1200

In this example, the BankAccount class uses a private field #balance to encapsulate the balance data and provide controlled access through public methods.

Polymorphism

Polymorphism allows objects of different classes to be treated as objects of a common superclass. It provides a way to perform a single action in different forms.

class Shape {
    area() {
        return 0;
    }
}

class Circle extends Shape {
    constructor(radius) {
        super();
        this.radius = radius;
    }

    area() {
        return Math.PI * this.radius ** 2;
    }
}

class Rectangle extends Shape {
    constructor(width, height) {
        super();
        this.width = width;
        this.height = height;
    }

    area() {
        return this.width * this.height;
    }
}

let shapes = [
    new Circle(10),
    new Rectangle(5, 10)
];

shapes.forEach(shape => {
    console.log(shape.area());
});
// Output:
// 314.1592653589793 (Area of the circle)
// 50 (Area of the rectangle)

In this example, the Shape class is the superclass, and Circle and Rectangle are subclasses. Each subclass provides its own implementation of the area method.

Object-Oriented JavaScript provides powerful features for structuring and managing code. By understanding and utilizing concepts such as objects, classes, inheritance, encapsulation, and polymorphism, you can write more organized, reusable, and maintainable code. Experiment with these OOP principles to enhance your JavaScript development skills and build robust web applications.

Previous Post
Newer Post

Leave A Comment

Need Help?