Skip to main content
TOPIC 2 OF 9 · 2 MIN READ

Constructor Functions

A constructor function is a function used to create objects and is invoked with the `new` keyword. It automates object creation and initializes properties.

Key concepts

Constructor Function

A function used to create objects, invoked with the `new` keyword. It automates object creation and initializes properties. Particularly useful for creating multiple instances of objects with shared properties and methods.

Step by step

Bulk Object Creation:

  • Constructor functions are particularly useful for creating multiple instances of objects with shared properties and methods.

Examples

Constructor Function Example:

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

const person1 = new Person('Alice', 25);
const person2 = new Person('Bob', 30);

person1.greet(); // Hello, my name is Alice
person2.greet(); // Hello, my name is Bob

Stuck on this one? Talk to Sumit.

Keys: F focus mode · ← → previous / next topic · Esc leave focus