Lecture Notes Of Day 18: JavaScript Classes and Object-Oriented Programming (OOP)

Rashmi Mishra
0

 Lecture Notes Of Day 18

JavaScript Classes and Object-Oriented Programming (OOP)

Objective:
The goal of this lesson is to understand the basic principles of Object-Oriented Programming (OOP) in JavaScript. We will dive into how classes and objects work, the role of constructors, methods in classes, and the this keyword.


1. Introduction to Object-Oriented Programming (OOP)

Object-Oriented Programming (OOP) is a programming paradigm that organizes code around objects rather than actions. The key concepts of OOP are:

  • Classes: Templates or blueprints for creating objects.
  • Objects: Instances of classes that contain both data (properties) and behavior (methods).
  • Encapsulation: Grouping related data and methods into a single unit or class.
  • Inheritance: Ability to create new classes based on existing ones.
  • Polymorphism: The ability to use the same method name with different implementations.

In JavaScript, we achieve OOP using classes, which are introduced in ES6 (ECMAScript 2015).


2. Classes and Constructors in JavaScript

What is a Class?

A class in JavaScript is a blueprint for creating objects with shared properties and methods. It encapsulates data and methods that operate on the data. A class is a way to define the structure and behavior of an object.

Syntax for Defining a Class

class Person {

    constructor(name, age) {

        this.name = name;

        this.age = age;

    }

}

  • class is the keyword used to define a class.
  • constructor is a special method that is automatically called when a new instance of the class is created. It is used to initialize the object with specific properties.

Example:

class Person {

    constructor(name, age) {

        this.name = name;

        this.age = age;

    }

}

 

let person1 = new Person('Alice', 25);

console.log(person1.name); // Outputs: Alice

console.log(person1.age);  // Outputs: 25

  • new Person() creates an instance of the Person class and invokes the constructor to initialize the object.

Key Points:

  • The constructor is a method inside the class that is invoked when a new object is created.
  • this inside the constructor refers to the instance of the class.

3. Methods in Classes

Methods are functions that are defined inside a class and are used to perform actions or operations on the object’s data.

Syntax for Defining Methods in Classes:

class Car {

    constructor(make, model) {

        this.make = make;

        this.model = model;

    }

 

    // Method to display car details

    displayDetails() {

        console.log(`Car: ${this.make} ${this.model}`);

    }

}

Example:

class Car {

    constructor(make, model) {

        this.make = make;

        this.model = model;

    }

 

    displayDetails() {

        console.log(`Car: ${this.make} ${this.model}`);

    }

}

 

let car1 = new Car('Toyota', 'Corolla');

car1.displayDetails();  // Outputs: Car: Toyota Corolla

Key Points:

  • Methods are functions that belong to a class and operate on its properties.
  • In the example above, displayDetails is a method that outputs information about the Car object.

4. The this Keyword

The this keyword refers to the current instance of the class. It allows access to the properties and methods of the class from within the class itself. The value of this depends on the context in which it is used.

this inside the constructor:

When used inside the constructor, this refers to the new object being created.

Example:

class Person {

    constructor(name, age) {

        this.name = name;  // 'this' refers to the current instance

        this.age = age;

    }

 

    greet() {

        console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);

    }

}

 

let person1 = new Person('Bob', 30);

person1.greet();  // Outputs: Hello, my name is Bob and I am 30 years old.

this inside methods:

In methods, this refers to the instance of the class from which the method was called.

Example with Multiple Methods:

class Person {

    constructor(name, age) {

        this.name = name;

        this.age = age;

    }

 

    greet() {

        console.log(`Hello, my name is ${this.name}.`);

    }

 

    introduce() {

        console.log(`I am ${this.age} years old.`);

    }

}

 

let person1 = new Person('John', 22);

person1.greet();    // Outputs: Hello, my name is John.

person1.introduce(); // Outputs: I am 22 years old.

Key Points about this:

  • Inside the constructor, this refers to the newly created object.
  • Inside methods, this refers to the current instance of the class.
  • Be careful: In arrow functions, this does not behave as expected because it does not bind to the instance of the class, but rather to the surrounding context.

Example of Arrow Function and this:

class Counter {

    constructor() {

        this.count = 0;

    }

 

    increment() {

        setInterval(() => {

            this.count++;  // 'this' correctly refers to the Counter object

            console.log(this.count);

        }, 1000);

    }

}

 

let counter = new Counter();

counter.increment();

In the example above, this.count works because arrow functions do not have their own this context, so it uses the this of the enclosing increment method.


5. Inheritance in JavaScript Classes (Bonus)

Inheritance is a feature of OOP that allows one class to inherit the properties and methods of another class. This is done using the extends keyword.

Syntax for Inheritance:

class ChildClass extends ParentClass {

    constructor() {

        super();  // Calls the constructor of the parent class

        // Additional properties for the child class

    }

}

Example:

class Animal {

    constructor(name) {

        this.name = name;

    }

 

    speak() {

        console.log(`${this.name} makes a sound.`);

    }

}

 

class Dog extends Animal {

    constructor(name, breed) {

        super(name);  // Call the parent class constructor

        this.breed = breed;

    }

 

    speak() {

        console.log(`${this.name} barks.`);

    }

}

 

let dog = new Dog('Buddy', 'Golden Retriever');

dog.speak();  // Outputs: Buddy barks.

  • Dog is a subclass that inherits from the Animal class.
  • super() calls the parent class constructor.

Conclusion

In this lesson, we covered the essential concepts of Object-Oriented Programming (OOP) in JavaScript, including:

  • Classes and constructors: Classes define blueprints for objects, and constructors initialize new objects.
  • Methods in classes: Methods are functions that belong to a class and perform operations on the data.
  • The this keyword: The this keyword refers to the current instance of the class and is used to access its properties and methods.

These concepts are fundamental to OOP in JavaScript and will help you write more modular, maintainable, and reusable code.


Key Takeaways:

  • Use classes to define blueprints for creating objects.
  • Use the constructor to initialize object properties.
  • Methods define the behavior of the objects.
  • this refers to the instance of the class.


Post a Comment

0Comments

Post a Comment (0)