Episode 5 of 11

Class Constructors

Initialize objects with custom data using the constructor method — pass arguments when creating instances to set their initial properties.

Class Constructors

Right now, every instance is identical. The constructor method lets you pass data when creating an instance to give each one unique properties.

The Constructor Method

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

var userOne = new User('Shaun', 'shaun@example.com');
var userTwo = new User('Mario', 'mario@example.com');

console.log(userOne.name);   // 'Shaun'
console.log(userTwo.name);   // 'Mario'
console.log(userOne.email);  // 'shaun@example.com'

How It Works

new User('Shaun', 'shaun@example.com')
    ↓
1. JavaScript creates a new empty object {}
2. Calls the constructor with the arguments
3. 'this' inside the constructor refers to the new object
4. this.name = 'Shaun' sets a property on the new object
5. this.email = 'shaun@example.com' sets another property
6. The new object is returned

Default Values

class User {
    constructor(name, email, role = 'subscriber') {
        this.name = name;
        this.email = email;
        this.role = role;
        this.score = 0;  // Always starts at 0
    }
}

var admin = new User('Shaun', 'shaun@example.com', 'admin');
var subscriber = new User('Mario', 'mario@example.com');

console.log(admin.role);       // 'admin'
console.log(subscriber.role);  // 'subscriber' (default)
console.log(admin.score);      // 0

Key Takeaways

  • The constructor method runs automatically when new is called
  • this inside the constructor refers to the new instance being created
  • Use parameters to pass custom data; use defaults for values that rarely change
  • Properties set without parameters (like score = 0) are the same for every instance