Curriculum
Module 22 // Core JavaScript
Class Syntax (ES6+)
Module Objective
Class sugar over prototypes, extends, super, static members, private fields
Mental Model Realtime Simulation
INTERACTIVE_CANVASEditor_Pane
Loading...
Console_Output
Waiting for output...
Practical Code Examples
// Example 1
// 1. Public vs Private Fields
class Account {
balance = 0; // Public field
#pin = 1234; // Private field (# prefix)
deposit(val) {
this.balance += val;
}
getSecret() {
return this.#pin;
}
}
const myAcc = new Account();
console.log(myAcc.balance); // 0
// console.log(myAcc.#pin); // ❌ Syntax Error!💡 Modern JS classes support **Private Fields** (using `#`). They cannot be accessed outside the class, providing true encapsulation.
// Example 2
// 2. Static Members
class MathUtils {
static PI = 3.14;
static double(n) {
return n * 2;
}
}
console.log(MathUtils.PI); // 3.14
// const mu = new MathUtils();
// console.log(mu.PI); // undefined💡 `static` properties and methods belong to the **Class itself**, not the instances. They are used for utility functions that don't need instance data.
// Example 3
// 3. Getters and Setters
class Person {
constructor(name) { this._name = name; }
get name() { return this._name.toUpperCase(); }
set name(val) { this._name = val; }
}
const p = new Person("subhajit");
console.log(p.name); // "SUBHAJIT"💡 Getters and setters allow you to run logic when a property is accessed or modified, while keeping the external API looking like a simple property.
Engine & Memory Architecture
Class Memory Layout
1. Function Object:
- In the Heap, a Class is actually stored as a Function object.
- Methods defined inside the class are automatically attached to the Class's
prototypeobject.
2. Private Fields Storage:
- Private fields (
#) are stored in a hidden WeakMap-like internal storage in the engine. - They do not show up when you log the object or use
Object.keys(), making them invisible to the rest of the RAM.
3. Inheritance Chain:
- When a class
extendsanother, the engine creates a link between the child Class object and the parent Class object. - Hardware: The
super()call handles the logic of initializing the parent's memory layout before the child's.