The Constructor Method
What you'll learn: How the special constructor() method initializes new class instances when you use the new keyword.
What Is the Constructor Method?
Every class can have one special method called constructor(). This method runs automatically whenever you create a new instance of the class using new. Think of it as the "setup crew" that runs before your object is ready to use—it initializes properties and prepares the new instance.
The constructor is where you typically set up instance properties (those unique to each object created from the class). When you call new ClassName(), JavaScript creates a new object and immediately runs the constructor method, passing along any arguments you provided.
How It Works
class Car {
constructor(brand, color) {
this.brand = brand;
this.color = color;
}
}
const myCar = new Car('Toyota', 'blue');
console.log(myCar.brand); // 'Toyota'
console.log(myCar.color); // 'blue'
When new Car('Toyota', 'blue') runs, JavaScript creates a fresh object and calls constructor('Toyota', 'blue'). Inside the constructor, this refers to that new object, so you can attach properties to it.
Key Details
- A class can have only one constructor method
- The constructor is optional—if you don't define one, JavaScript uses a default empty constructor
- The constructor automatically returns the new instance (you don't need a
returnstatement)
Key Takeaway: The constructor() method is the initialization function that runs once when creating new class instances, setting up their initial properties and state.