Constructor Method
A constructor method is a special method used inside a class to initialize object properties when a new object is created.
Constructor Syntax (ES6 Class)
Creating an Object Using Constructor
Output
Constructor Without Parameters
Constructor with Default Values
A constructor runs automatically when an object is created from a class.
Why Do We Need a Constructor?
Constructors help to:
- Initialize object data
- Assign default values
- Set up an object when it is created
Without a constructor, objects would have no initial state.
Constructor Syntax (ES6 Class)
class Person { constructor(name, age) { this.name = name; this.age = age; }}Creating an Object Using Constructor
const person1 = new Person("Rahul", 25);const person2 = new Person("Anjali", 22);
console.log(person1.name, person1.age);console.log(person2.name, person2.age);Output
Rahul 25Anjali 22- Constructor executes automatically
- this refers to the current object
Key Point
- A class can have only one constructor
- Constructor name must be constructor
- It executes automatically when new keyword is used
- Constructor cannot be called manually
Constructor Without Parameters
class Car { constructor() { this.brand = "Toyota"; }}
const car1 = new Car();console.log(car1.brand);Constructor with Default Values
class User { constructor(name = "Guest") { this.name = name; }}
const user1 = new User();const user2 = new User("Nikhil");
console.log(user1.name); // Guestconsole.log(user2.name); // NikhilConstructor in Inheritance (super( ))
When using inheritance, the child class must call super().
class Animal { constructor(name) { this.name = name; }}
class Dog extends Animal { constructor(name, breed) { super(name); this.breed = breed; }}
const dog1 = new Dog("Buddy", "Labrador");console.log(dog1.name, dog1.breed);- super() calls parent constructor
- Mandatory before using this
When to Use Constructor
- When creating multiple objects with similar structure
- When initializing object properties
- When working with classes and inheritance
Two Minute Drill
- Constructor initializes object properties
- It runs automatically with new
- Only one constructor per calss
- this refers to the current object
- super( ) is required in child classes
- Constructor does not return values
Need more clarification?
Drop us an email at career@quipoinfotech.com
