JAVASCRIPT

JavaScript Constructor: Class Constructors in JS

In JavaScript, constructors are special functions to initialize objects within classes. Constructor functions enable the creation of instances of classes with the same structure but different data.

How to Use JavaScript Constructors

You can define a constructor using the constructor method within a class definition. This method includes parameters and initialization code to set up the object. Here’s the basic syntax:

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

To create an instance of your class, you use the new keyword. Essentially, new creates an object of the class by allocating memory for it and calling the constructor method:

let myCar = new Car("VW");
  • class: The keyword to define a class in JavaScript.
  • constructor: A special method for creating and initializing an object instance of that class.
  • this: The keyword to reference the new object.
  • new: The keyword to create an instance of a class, which triggers the constructor.

When to Use a Constructor in JavaScript

Constructors are helpful in many object creation scenarios.

Instance Creation

Constructors are useful when you need to create multiple objects with similar properties and methods but different values.

let car1 = new Car("Honda");
let car2 = new Car("Ford");

Initializing Properties

Constructors allow you to initialize any properties you need for an object’s methods to function.

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

let user1 = new User('Alice', 30);
user1.greet();  // Outputs: Hello, my name is Alice and I am 30 years old.

Encapsulating Code

You can use constructors to encapsulate the setup logic required to create a fully formed object, which can include calling methods or conditional logic.

class Account {
    constructor(owner) {
        this.owner = owner;
        this.balance = 0;
    }
    deposit(amount) {
        this.balance += amount;
        console.log(`${amount} added to the balance.`);
    }
}

Examples of Using Constructors in JavaScript

E-commerce Product Initialization

Constructors can define product objects in an e-commerce platform, setting properties like price, description, and inventory.

class Product {
    constructor(name, price) {
        this.name = name;
        this.price = price;
    }
    applyDiscount(discount) {
        this.price -= discount;
        console.log(`New price is ${this.price}`);
    }
}

let newProduct = new Product('Bluetooth Speaker', 149);
newProduct.applyDiscount(20);

Gaming Characters

In video games, constructors can be used to create character objects with specific attributes and abilities.

class Character {
    constructor(type, strength, intelligence) {
        this.type = type;
        this.strength = strength;
        this.intelligence = intelligence;
    }
    attack() {
        console.log(`${this.type} attacks with strength ${this.strength}`);
    }
}

let warrior = new Character('Warrior', 10, 5);
warrior.attack();

User Management System

Constructors can manage user profiles in systems, initializing with user-specific data such as usernames, passwords, and roles.

class User {
    constructor(username, password, role) {
        this.username = username;
        this.password = password;
        this.role = role;
    }
    authenticate() {
        console.log(`User ${this.username} authenticated.`);
    }
}

let admin = new User('adminUser', 'adminPass', 'Admin');
admin.authenticate();

Learn More About Constructors and Objects in JavaScript

Default Constructors in JavaScript

In JavaScript, if you don't explicitly define a constructor method within a class, JavaScript automatically provides a default constructor. A default constructor is a no-argument constructor that initializes a new object with default values if no properties are specified.

For classes that extend another class, the default constructor calls the parent class's constructor, passing along any arguments that were provided:

class Vehicle {
    constructor() {
        this.type = 'Vehicle';
    }
}

class Car extends Vehicle {
    // No constructor defined here, so JavaScript uses a default constructor
}

let myCar = new Car();
console.log(myCar.type);  // Outputs: "Vehicle"

This default behavior ensures that even without a detailed constructor, objects are constructed properly with inherited properties when using class-based inheritance. It simplifies scenarios where no specific constructor logic is necessary, allowing developers to focus on more complex initialization scenarios where specific property settings are required.

Inheritance with Constructors

JavaScript constructors play a crucial role in inheritance, where a subclass can call the constructor of its parent class to extend its functionality.

class Vehicle {
  constructor(brand) {
    this.brand = brand;
  }
}

class Car extends Vehicle {
  constructor(brand, model) {
    super(brand);
    this.model = model;
  }
}

Constructor Overloading

Unlike some other languages, JavaScript does not support constructor overloading directly. To simulate this, you can use optional parameters or check argument types within a single constructor.

class Box {
  constructor(width, height, length) {
    this.width = width || 50;  // Default width is 50 if undefined
    this.height = height || 50;  // Default height is 50 if undefined
    this.length = length || 50;  // Default length is 50 if undefined
  }
}
Learn JavaScript for Free
Start learning now
button icon
To advance beyond this tutorial and learn JavaScript by doing, try the interactive experience of Mimo. Whether you're starting from scratch or brushing up your coding skills, Mimo helps you take your coding journey above and beyond.

Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.

You can code, too.

© 2024 Mimo GmbH