Class Syntax & Constructor Methods
Class Syntax & Constructor Methods in Modern JavaScript
Introduced in ECMAScript 2015 (ES6), the class syntax provides a clean, declarative syntax over JavaScript's existing prototype-based inheritance model. While classes in JavaScript are syntactic sugar over prototypes, they introduce strict semantics, constructor encapsulation, and class-level invariants.
1. Class Declaration & The constructor Method
A class defines the blueprint for objects. The constructor() method is a special function that runs automatically whenever a new instance is created via the new operator:
2. Key Differences Between Classes & Constructor Functions
| Feature | ES6 Class | Constructor Function (function Account()) |
|---|---|---|
| Strict Mode | Automatically runs in 'use strict' | Non-strict unless explicitly declared |
Invocation without new | Throws TypeError immediately | Fails silently and pollutes global window |
| Hoisting | Temporal Dead Zone (Cannot instantiate before declaration) | Hoisted (Can be called before definition) |
| Method Enumerability | Methods on prototype are non-enumerable | Prototype methods are enumerable by default |
3. Subclassing with extends and super()
To inherit from an existing class, use extends. The subclass constructor must invoke super() before accessing this:
this before calling super() results in a ReferenceError: Must call super constructor in derived class before accessing 'this'.Practice Quiz
Getters, Setters & Static Methods
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Scope Chain & Lexical Environment | Getters, Setters & Static Methods |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.