Episode 31 of 46

JavaScript Constructor Function

Learn how to create blueprints for objects with constructor functions and classes.

A constructor function is a blueprint for creating multiple objects with the same structure. It's the traditional way to do object-oriented programming in JavaScript.

Constructor Functions

function User(name, age, email) {
    this.name = name;
    this.age = age;
    this.email = email;
    this.greet = function() {
        console.log(`Hi, I'm ${this.name}`);
    };
}

// Create instances with "new"
let user1 = new User("Alice", 25, "alice@example.com");
let user2 = new User("Bob", 30, "bob@example.com");

user1.greet();  // "Hi, I'm Alice"
user2.greet();  // "Hi, I'm Bob"

The new Keyword

When you call a function with new, JavaScript:

  1. Creates a new empty object
  2. Sets this to point to that object
  3. Runs the function code
  4. Returns the object

ES6 Classes (Modern Way)

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

    greet() {
        console.log(`Hi, I'm ${this.name}`);
    }

    getInfo() {
        return `${this.name}, age ${this.age}`;
    }
}

let user1 = new User("Alice", 25, "alice@example.com");
user1.greet();     // "Hi, I'm Alice"
console.log(user1.getInfo()); // "Alice, age 25"

instanceof

console.log(user1 instanceof User);  // true