JavaScript Object Constructors

Creating objects with constructor functions

🏗️ What are Object Constructors?

Object constructors are functions that create and initialize objects. They serve as templates for creating multiple objects with similar properties and methods.


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

// Create objects
const person1 = new Person("Alice", 25);
const person2 = new Person("Bob", 30);
                                    

Output:

person1: {name: "Alice", age: 25}

person2: {name: "Bob", age: 30}

Constructor Function Features

🔧

Function Template

Reusable template for creating objects

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

new Keyword

Creates new instances of objects

const myCar = new Car("Toyota", "Camry");
🎯

this Keyword

Refers to the current object instance

this.property = value;
🔄

Multiple Instances

Create many objects from one template

const car1 = new Car("Honda", "Civic");
const car2 = new Car("Ford", "Focus");

🔹 Basic Constructor Function

A constructor function is a regular function used with the 'new' keyword:

// Constructor function (starts with capital letter)
function Student(name, grade, subject) {
    this.name = name;
    this.grade = grade;
    this.subject = subject;
    
    // Method inside constructor
    this.getInfo = function() {
        return this.name + " studies " + this.subject;
    };
}

// Create student objects
const student1 = new Student("Emma", "A", "Math");
const student2 = new Student("John", "B", "Science");

console.log(student1.getInfo()); // "Emma studies Math"
console.log(student2.name);      // "John"

Output:

Emma studies Math

John

🔹 Constructor with Methods

Add methods to constructor functions for object behavior:

function BankAccount(owner, balance) {
    this.owner = owner;
    this.balance = balance;
    
    // Deposit method
    this.deposit = function(amount) {
        this.balance += amount;
        return "Deposited $" + amount + ". New balance: $" + this.balance;
    };
    
    // Withdraw method
    this.withdraw = function(amount) {
        if (amount <= this.balance) {
            this.balance -= amount;
            return "Withdrew $" + amount + ". New balance: $" + this.balance;
        } else {
            return "Insufficient funds!";
        }
    };
}

const account = new BankAccount("Alice", 1000);
console.log(account.deposit(500));  // "Deposited $500. New balance: $1500"
console.log(account.withdraw(200)); // "Withdrew $200. New balance: $1300"

Output:

Deposited $500. New balance: $1500

Withdrew $200. New balance: $1300

🔹 Constructor vs Object Literal

Compare constructor functions with object literals:

// Object Literal (single object)
const book1 = {
    title: "JavaScript Guide",
    author: "John Doe",
    pages: 300
};

// Constructor Function (template for multiple objects)
function Book(title, author, pages) {
    this.title = title;
    this.author = author;
    this.pages = pages;
    this.getDescription = function() {
        return this.title + " by " + this.author + " (" + this.pages + " pages)";
    };
}

// Create multiple books easily
const book2 = new Book("Python Basics", "Jane Smith", 250);
const book3 = new Book("Web Development", "Mike Johnson", 400);

console.log(book2.getDescription());
console.log(book3.getDescription());

Output:

Python Basics by Jane Smith (250 pages)

Web Development by Mike Johnson (400 pages)

🧠 Test Your Knowledge

What keyword is used to create an object from a constructor function?