Constructor & Method

JavaScript Constructor and Method Tutorial

Table of Contents

  1. Introduction to Constructors and Methods in JavaScript

  2. What is a Constructor?

    • Defining a Constructor Function

    • Using ES6 Classes for Constructors

    • Initializing Object Properties with Constructors

  3. What is a Method?

    • Defining Methods in Constructor Functions

    • Defining Methods in ES6 Classes

  4. Creating Objects with Constructors and Methods

  5. Practical Examples

    • Basic Constructor and Method Example

    • Real-World Example: Creating a Car Object

  6. The this Keyword in Constructors and Methods

  7. Adding Methods to Constructors After Creation

  8. Method Overriding in Classes

  9. Conclusion


1. Introduction to Constructors and Methods in JavaScript

Welcome to the Codes with Pankaj tutorial on Constructors and Methods in JavaScript! In this tutorial, we'll explore how to use constructors and methods to create and manipulate objects in JavaScript. These concepts are fundamental to object-oriented programming (OOP) and help organize your code. Let’s dive in!

2. What is a Constructor?

A constructor is a special function used to initialize an object when it is created. Constructors allow you to set the initial state of an object by assigning values to its properties.

Defining a Constructor Function

Before ES6, constructors were typically defined using regular functions.

Example:

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

In this example, the Person function serves as a constructor that initializes the name and age properties of the object.

Using ES6 Classes for Constructors

With ES6, JavaScript introduced classes, which provide a cleaner and more concise way to define constructors.

Example:

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

This class-based syntax is functionally the same as the function-based constructor but offers a more intuitive way to work with objects.

Initializing Object Properties with Constructors

When you create a new object using the new keyword, the constructor is called to initialize the object's properties.

Example:

let person1 = new Person("Alice", 30);
console.log(person1.name);  // Output: Alice
console.log(person1.age);   // Output: 30

3. What is a Method?

A method is a function that is defined within an object or a class. Methods define the behavior of an object, allowing it to perform actions.

Defining Methods in Constructor Functions

You can define methods directly within a constructor function.

Example:

function Person(name, age) {
    this.name = name;
    this.age = age;

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

Defining Methods in ES6 Classes

In ES6 classes, methods are defined inside the class without the function keyword.

Example:

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

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

4. Creating Objects with Constructors and Methods

Once you've defined a constructor and methods, you can create objects and call their methods.

Example:

let person1 = new Person("Bob", 25);
person1.greet();  // Output: Hello, my name is Bob.

5. Practical Examples

Basic Constructor and Method Example

function Car(brand, model) {
    this.brand = brand;
    this.model = model;

    this.getDetails = function() {
        return `${this.brand} ${this.model}`;
    };
}

let car1 = new Car("Toyota", "Camry");
console.log(car1.getDetails());  // Output: Toyota Camry

Real-World Example: Creating a Car Object

class Car {
    constructor(brand, model, year) {
        this.brand = brand;
        this.model = model;
        this.year = year;
    }

    startEngine() {
        console.log(`${this.brand} ${this.model} is starting.`);
    }

    getCarInfo() {
        return `${this.year} ${this.brand} ${this.model}`;
    }
}

let car1 = new Car("Honda", "Civic", 2021);
car1.startEngine();  // Output: Honda Civic is starting.
console.log(car1.getCarInfo());  // Output: 2021 Honda Civic

6. The this Keyword in Constructors and Methods

The this keyword refers to the current object instance. In constructors, this is used to initialize the object's properties, and in methods, it refers to the object that called the method.

Example:

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

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

let person1 = new Person("Alice", 25);
person1.greet();  // Output: Hello, my name is Alice.

7. Adding Methods to Constructors After Creation

You can add methods to objects created by a constructor even after the object is created.

Example:

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

Person.prototype.sayGoodbye = function() {
    console.log(`${this.name} says goodbye.`);
};

let person1 = new Person("Charlie", 28);
person1.sayGoodbye();  // Output: Charlie says goodbye.

8. Method Overriding in Classes

You can override methods in child classes that were defined in parent classes.

Example:

class Animal {
    speak() {
        console.log("Animal makes a sound.");
    }
}

class Dog extends Animal {
    speak() {
        console.log("Dog barks.");
    }
}

let dog = new Dog();
dog.speak();  // Output: Dog barks.

9. Conclusion

In this detailed tutorial, we've explored constructors and methods in JavaScript, which are fundamental concepts for creating and manipulating objects. By understanding how to use constructors to initialize properties and methods to define behavior, you can write more organized and reusable code.

For more tutorials and examples, visit www.codeswithpankaj.com! Happy coding!


Last updated