The Constructor Method
What you'll learn: How to define a constructor method inside a class that automatically runs when you create new instances with new.
What Is the Constructor Method?
The constructor method is a special method inside a class that runs automatically whenever you create a new instance using the new operator. Think of it as the "setup instructions" for your object — it's where you initialize properties and prepare the object for use.
When JavaScript executes new MyClass(), it looks for a method named constructor inside that class and calls it, passing along any arguments you provided.
Defining a Constructor
class Car {
constructor(brand, model) {
this.brand = brand;
this.model = model;
this.mileage = 0;
}
}
const myCar = new Car('Toyota', 'Camry');
console.log(myCar.brand); // "Toyota"
console.log(myCar.model); // "Camry"
console.log(myCar.mileage); // 0
Notice how constructor accepts parameters (brand, model) and uses this to assign properties to the new instance. Every time you call new Car(...), the constructor runs and sets up that specific car object.
Key Details
- One per class: A class can only have one constructor method
- Optional: If you don't define a constructor, JavaScript provides a default empty one
- No return needed: The constructor automatically returns the new instance (just like constructor functions with
new)
Key Takeaway: The constructor method is the special setup function inside a class that runs when you create instances with new, letting you initialize properties and accept parameters.