Constructor
Constructor
Section titled “Constructor”Introduction
Section titled “Introduction”The constructor method is a special method that runs automatically when a new instance is created with new. It’s where you set up instance properties and perform initialization.
Basic Constructor
Section titled “Basic Constructor”class User { constructor(name, email) { this.name = name; this.email = email; this.createdAt = new Date(); }}
const user = new User('Alice', 'alice@email.com');console.log(user.name); // 'Alice'console.log(user.createdAt); // Date objectDefault Values
Section titled “Default Values”class Config { constructor(theme = 'dark', lang = 'en') { this.theme = theme; this.lang = lang; this.version = '1.0.0'; }}
const defaultConfig = new Config();console.log(defaultConfig.theme); // 'dark'
const customConfig = new Config('light', 'fr');console.log(customConfig.theme); // 'light'Validation in Constructor
Section titled “Validation in Constructor”class BankAccount { constructor(owner, initialBalance = 0) { if (!owner) throw new Error('Owner is required'); if (initialBalance < 0) throw new Error('Balance cannot be negative');
this.owner = owner; this.balance = initialBalance; }}
// Validconst account = new BankAccount('Alice', 1000);
// Throwsconst invalid = new BankAccount('', -500); // Error!super() in Subclass Constructors
Section titled “super() in Subclass Constructors”class Animal { constructor(name) { this.name = name; }}
class Dog extends Animal { constructor(name, breed) { super(name); // Must call super before using this this.breed = breed; }}
const rex = new Dog('Rex', 'Labrador');console.log(rex.name); // 'Rex'console.log(rex.breed); // 'Labrador'super() Requirements
Section titled “super() Requirements”- Must call
super()before accessingthis - If a subclass defines a constructor, it must call
super() - If no constructor is defined in a subclass,
super()is automatically called
class Animal { constructor(name) { this.name = name; }}
class Dog extends Animal { // ❌ constructor(name, breed) { this.breed = breed; } // ReferenceError: Must call super before accessing this
constructor(name, breed) { super(name); // ✅ Required this.breed = breed; }}Default Constructor
Section titled “Default Constructor”If you don’t define a constructor, JavaScript provides a default one:
class User { // Default constructor is equivalent to: // constructor() {} greet() { return 'Hello!'; }}
const user = new User(); // works fineconsole.log(user.greet()); // 'Hello!'Summary
Section titled “Summary”constructor()runs once when a new instance is created- Default values and validation can be done in the constructor
- Subclass constructors must call
super()beforethis - Without a constructor, JS provides a default one