Scalable Business for Startups

Get the oars in the water and start rowing. Execution is the single biggest factor in achievement so the faster and better your execution.

+91 9472774549 thebytemind@gmail.com Looking for collaboration for your next creative project?

Chapter 9: Objects and Object-Oriented Programming

In JavaScript, objects are essential data structures that help you manage and organize data efficiently. Object-Oriented Programming (OOP) brings principles such as encapsulation, inheritance, and polymorphism, enabling more structured and modular code. This chapter will guide you through JavaScript's object handling and OOP fundamentals, complete with examples to illustrate these powerful concepts.

1. Introduction to JavaScript Objects

  • An object is a collection of properties, where each property is defined by a key-value pair.
  • Properties can hold values such as numbers, strings, arrays, or even other objects.
  • Syntax:
        
            let person = {
                name: "John",
                age: 30,
                greet: function() {
                    console.log("Hello, " + this.name);
                }
            };
        
    
Example:
        
let car = {
    brand: "Toyota",
    model: "Corolla",
    year: 2020,
    displayInfo: function() {
        console.log(`Car: ${this.brand} ${this.model}, Year: ${this.year}`);
    }
};

car.displayInfo();  // Output: Car: Toyota Corolla, Year: 2020
        
    

2. Creating and Modifying Objects

You can create objects directly with literals or use the new Object() syntax. Properties can be added or removed dynamically.

Example: Adding and Deleting Properties
        
let book = {};
book.title = "JavaScript Essentials";
book.author = "Jane Doe";
console.log(book);  // Output: { title: 'JavaScript Essentials', author: 'Jane Doe' }

delete book.author;
console.log(book);  // Output: { title: 'JavaScript Essentials' }
        
    

3. Object Constructors

  • Constructors are special functions for creating objects with a similar structure.
  • The this keyword in a constructor function refers to the instance created by that function.
Example:
        
function Animal(name, species) {
    this.name = name;
    this.species = species;
    this.describe = function() {
        console.log(`This is ${this.name} the ${this.species}`);
    };
}

let animal1 = new Animal("Buddy", "Dog");
animal1.describe();  // Output: This is Buddy the Dog
        
    

4. Prototypes and Prototype Chain

  • Every JavaScript object has a prototype, an object it inherits properties and methods from.
  • Methods and properties defined in the prototype are shared across all instances.
Example:
        
function Car(make, model) {
    this.make = make;
    this.model = model;
}

Car.prototype.displayDetails = function() {
    console.log(`Car: ${this.make} ${this.model}`);
};

let myCar = new Car("Ford", "Mustang");
myCar.displayDetails();  // Output: Car: Ford Mustang
        
    

5. Object-Oriented Principles in JavaScript

a. Encapsulation

Encapsulation is the practice of bundling data and methods within a single unit (the object), restricting direct access to certain details.

Example:
        
function BankAccount(balance) {
    this._balance = balance;

    this.deposit = function(amount) {
        if (amount > 0) this._balance += amount;
    };

    this.getBalance = function() {
        return this._balance;
    };
}

let account = new BankAccount(1000);
account.deposit(500);
console.log(account.getBalance());  // Output: 1500
        
    
b. Inheritance

Inheritance enables one class to inherit properties and methods from another, allowing code reuse. JavaScript uses prototypes to enable inheritance.

Example:
        
function Person(name) {
    this.name = name;
}

Person.prototype.greet = function() {
    console.log("Hello, " + this.name);
};

function Student(name, grade) {
    Person.call(this, name);
    this.grade = grade;
}

Student.prototype = Object.create(Person.prototype);
Student.prototype.constructor = Student;

let student = new Student("Alice", "A");
student.greet();  // Output: Hello, Alice
        
    
c. Polymorphism

Polymorphism allows objects to be treated as instances of their parent class. In JavaScript, polymorphism can be achieved through method overriding.

Example:
        
function Employee(name) {
    this.name = name;
}

Employee.prototype.work = function() {
    console.log(this.name + " is working");
};

function Developer(name, skill) {
    Employee.call(this, name);
    this.skill = skill;
}

Developer.prototype = Object.create(Employee.prototype);
Developer.prototype.constructor = Developer;

Developer.prototype.work = function() {
    console.log(this.name + " is coding in " + this.skill);
};

let dev = new Developer("Bob", "JavaScript");
dev.work();  // Output: Bob is coding in JavaScript
        
    

6. Classes in ES6

  • JavaScript ES6 introduced the class syntax, simplifying object-oriented patterns with constructors, methods, and inheritance.
Example:
        
class Rectangle {
    constructor(width, height) {
        this.width = width;
        this.height = height;
    }

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

let rect = new Rectangle(10, 5);
console.log(rect.area());  // Output: 50
        
    

Key Takeaways

  • Objects store data with properties and methods, providing modularity in code.
  • Constructors and prototypes enable efficient object creation and inheritance.
  • Encapsulation, inheritance, and polymorphism are key OOP principles that can be implemented in JavaScript.
  • ES6 classes offer a clearer and more structured syntax for OOP.