JavaScript Classes: Complete Guide to Syntax, Inheritance, and Private Fields
Master modern JavaScript ES6+ classes: constructors, methods, getters/setters, private identifiers (#), static blocks, prototypal inheritance under the hood, and production architectural patterns.

JavaScript Classes: Complete Guide to Syntax, Inheritance, and Private Fields — Legion Mind Architecture Dispatch
Key Architecture Takeaways
- ES6 classes are syntactic sugar over JavaScript's existing prototype-based inheritance model.
- The constructor method executes during instantiation; subclasses must call super() before accessing this.
- Modern ES2022 private fields (#field) enforce true encapsulation at the engine level without closures.
- Class methods live on the prototype chain, while arrow field properties create per-instance function copies.
Introduced in ECMAScript 2015 (ES6) and expanded extensively through ES2022, classes in JavaScript provide a clean, declarative syntax for object-oriented programming (OOP). If you come from languages like Java, C#, or Python, JavaScript class syntax will feel instantly familiar.
However, JavaScript is fundamentally a prototype-based language. Underneath the syntactic sugar, JavaScript classes do not create traditional rigid class types—they build and wire objects using JavaScript's native prototype chain. Understanding both the clean syntax and the underlying engine mechanics is what separates junior developers from senior software engineers.
1. Prototype vs Class: What Happens Under the Hood?
Before ES6, JavaScript developers created blueprints using constructor functions and manually attached methods to the function's .prototype object:
// The Pre-ES6 Constructor Function Pattern
function LegacyUser(name, email) {
this.name = name;
this.email = email;
}
LegacyUser.prototype.getDisplayName = function () {
return `${this.name} <${this.email}>`;
};
const userA = new LegacyUser("Sarah Connor", "sarah@example.com");
console.log(userA.getDisplayName()); // "Sarah Connor <sarah@example.com>"
The modern class declaration provides identical prototype delegation, but with stricter guarantees, cleaner readability, and built-in protections:
// The Modern ES6+ Class Pattern
class User {
constructor(name, email) {
this.name = name;
this.email = email;
}
getDisplayName() {
return `${this.name} <${this.email}>`;
}
}
const userB = new User("John Connor", "john@example.com");
console.log(typeof User); // "function" — classes are specialized constructor functions
console.log(userB instanceof User); // true
console.log(Object.getPrototypeOf(userB) === User.prototype); // true
Key Differences Between Classes and Constructor Functions
| Feature | ES5 Constructor Functions | ES6+ Classes |
|---|---|---|
Invocation without new | Fails silently or pollutes global this | Throws TypeError: Class constructor cannot be invoked without 'new' |
| Execution Mode | Inherits caller context (loose or strict) | Body is always executed in strict mode ("use strict") |
| Hoisting | Fully hoisted (can call before definition) | Hoisted into Temporal Dead Zone (TDZ) (cannot use before declaration) |
| Method Enumerability | Methods on .prototype are enumerable by default | Methods are non-enumerable by default (Object.keys skips them) |
2. Anatomy of a Class: Constructors, Methods & Accessors
A class definition can contain constructor logic, instance methods, computed properties, and getters/setters.
class BankAccount {
// 1. Constructor: runs once when instantiated with `new BankAccount()`
constructor(accountHolder, initialBalance = 0) {
this.accountHolder = accountHolder;
this._balance = initialBalance; // Convention for internal property
}
// 2. Getter: allows accessing computed values as if they were properties
get balance() {
return `$${this._balance.toFixed(2)}`;
}
// 3. Setter: enables validation before mutating state
set balance(amount) {
if (typeof amount !== "number" || amount < 0) {
throw new RangeError("Balance must be a positive number.");
}
this._balance = amount;
}
// 4. Instance Method: shared across all instances on BankAccount.prototype
deposit(amount) {
if (amount <= 0) {
throw new Error("Deposit amount must be greater than zero.");
}
this._balance += amount;
return this._balance;
}
}
const account = new BankAccount("Alice", 150);
console.log(account.balance); // "$150.00" (invokes getter)
account.deposit(50);
console.log(account.balance); // "$200.00"
account.balance = 300; // Invokes setter
console.log(account.balance); // "$300.00"
3. Modern ES2022 Features: Private Fields and Static Blocks
Historically, JavaScript lacked native privacy; developers used underscores (_property) or WeakMap hacks. ES2022 officially standardized hard private fields, methods, and accessors using the # hash prefix.
Private Fields (#field)
Private fields cannot be accessed, inspected, or modified from outside the class boundary. Attempting to access #field externally throws a syntax error at compile/parse time:
class SecurePaymentGateway {
// Public field
merchantId;
// Hard private field (engine-enforced)
#apiKey;
#requestCount = 0;
constructor(merchantId, apiKey) {
this.merchantId = merchantId;
this.#apiKey = apiKey;
}
// Hard private helper method
#signPayload(payload) {
this.#requestCount++;
return `SIGNED[${this.#apiKey}]:${JSON.stringify(payload)}`;
}
// Public method exposing safe functionality
processTransaction(payload) {
const signedData = this.#signPayload(payload);
return { status: "success", signedData, requests: this.#requestCount };
}
}
const gateway = new SecurePaymentGateway("merch_9921", "sk_live_secret_token_123");
console.log(gateway.merchantId); // "merch_9921"
// console.log(gateway.#apiKey); // SyntaxError: Private field '#apiKey' must be declared in an enclosing class
Static Methods, Properties, and Static Initialization Blocks
Static members belong to the class constructor itself, not to individual instances. ES2022 also introduced static initialization blocks for running setup logic:
class ConfigurationManager {
static defaultTimeout = 5000;
static supportedRegions = ["us-east-1", "eu-central-1", "ap-southeast-1"];
// Static initialization block runs once when the class is evaluated
static {
try {
if (typeof process !== "undefined" && process.env?.APP_REGION) {
this.currentRegion = process.env.APP_REGION;
} else {
this.currentRegion = this.supportedRegions[0];
}
} catch {
this.currentRegion = "us-east-1";
}
}
static isRegionSupported(region) {
return this.supportedRegions.includes(region);
}
}
console.log(ConfigurationManager.currentRegion); // "us-east-1"
console.log(ConfigurationManager.isRegionSupported("eu-central-1")); // true
4. Inheritance and Polymorphism: extends and super
JavaScript classes use the extends keyword to establish inheritance between a subclass and a superclass.
class BaseService {
constructor(serviceName, timeoutMs = 3000) {
this.serviceName = serviceName;
this.timeoutMs = timeoutMs;
}
connect() {
console.log(`[${this.serviceName}] Establishing network connection...`);
}
healthCheck() {
return { service: this.serviceName, status: "healthy" };
}
}
class RedisCacheService extends BaseService {
constructor(host, port, timeoutMs) {
// CRITICAL: super() must be called before accessing 'this'
super("RedisCache", timeoutMs);
this.host = host;
this.port = port;
}
// Method overriding (Polymorphism)
connect() {
// Optionally call parent logic
super.connect();
console.log(`[${this.serviceName}] Connected to socket ${this.host}:${this.port}`);
}
flushAll() {
console.log(`[${this.serviceName}] Invalidation cache completed.`);
}
}
const redis = new RedisCacheService("127.0.0.1", 6379, 5000);
redis.connect();
// Output:
// [RedisCache] Establishing network connection...
// [RedisCache] Connected to socket 127.0.0.1:6379
console.log(redis.healthCheck()); // { service: 'RedisCache', status: 'healthy' }
[!WARNING] The
super()Constructor Rule: In derived classes (subclasses), you must callsuper()before accessingthis. If you referencethisbefore callingsuper(), JavaScript throws aReferenceError: Must call super constructor in derived class before accessing 'this'.
5. Critical Pitfall: The this Binding Context
One of the most common bugs in JavaScript classes is losing the this context when passing a class method as a callback or event handler.
The Problem
class ButtonController {
constructor(label) {
this.label = label;
}
handleClick() {
console.log(`Button clicked: ${this.label}`);
}
}
const btn = new ButtonController("Submit Form");
// Passing the method directly as a callback:
setTimeout(btn.handleClick, 100);
// Output in browser: TypeError: Cannot read properties of undefined (reading 'label')
// Why? In strict mode, detached methods lose their binding, and 'this' becomes undefined.
The Solutions
There are three ways to solve this context loss:
// Solution 1: Bind in the constructor (Memory efficient for many instances)
class BoundController {
constructor(label) {
this.label = label;
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
console.log(`Clicked: ${this.label}`);
}
}
// Solution 2: Class field with arrow function (Convenient, auto-binds 'this')
class ArrowFieldController {
constructor(label) {
this.label = label;
}
handleClick = () => {
console.log(`Clicked: ${this.label}`);
};
}
// Solution 3: Inline arrow function at call-site
setTimeout(() => btn.handleClick(), 100);
[!NOTE] Memory Trade-off: Standard class methods (
handleClick() {}) reside onButtonController.prototype, consuming memory once across 10,000 instances. Arrow function fields (handleClick = () => {}) are instantiated as separate function objects on every single instance. For a singleton service, arrow fields are great; for hundreds of thousands of data records, use prototype methods.
6. Production Blueprint: An Enterprise HTTP Client Class
Here is how modern JavaScript classes are structured in production enterprise environments, encapsulating auth headers, rate-limit retry logic, and interceptors:
// Production API Client Example
class ApiClient {
readonly #baseUrl: string;
#authToken: string | null = null;
static #defaultHeaders = {
"Content-Type": "application/json",
Accept: "application/json",
};
constructor(baseUrl: string) {
if (!baseUrl.startsWith("http")) {
throw new Error(`Invalid baseUrl: ${baseUrl}`);
}
this.#baseUrl = baseUrl.replace(/\/$/, "");
}
setAuthorizationToken(token: string): void {
this.#authToken = token;
}
async request<T>(endpoint: string, options: RequestInit = {}): Promise<T> {
const url = `${this.#baseUrl}/${endpoint.replace(/^\//, "")}`;
const headers: Record<string, string> = {
...ApiClient.#defaultHeaders,
...(options.headers as Record<string, string>),
};
if (this.#authToken) {
headers["Authorization"] = `Bearer ${this.#authToken}`;
}
const response = await fetch(url, { ...options, headers });
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
return response.json() as Promise<T>;
}
}
// Usage
const api = new ApiClient("https://api.legionmind.si/v1");
api.setAuthorizationToken("lm_prod_token_8849");
// const data = await api.request("/health");
7. Official Documentation & Video Resources
To deepen your mastery of JavaScript prototypes and modern OOP architecture, explore these vetted resources:
- MDN Web Docs: Classes Reference
- MDN Web Docs: Private Properties & Methods
- ECMAScript Specification: TC39 Class Definitions Specification
- Recommended Video Guide: JavaScript Classes in 100 Seconds & Beyond (Fireship)
- Deep Dive Video: Prototypes vs Classes: How JavaScript OOP Actually Works (Web Dev Simplified)
Conclusion
JavaScript classes bring clarity, maintainability, and clean inheritance abstractions to complex codebases. By leveraging modern ES2022 #private fields, static blocks, and understanding how prototype delegation handles methods in memory, you can design scalable, bulletproof software architectures across Node.js, Next.js, and browser environments.
Related Technical Dispatches
Production Runbooks & Architecture Notes
Monthly technical dispatches covering Linux VPS hardening, strict DMARC deliverability, Next.js optimization, and cloud operations. Zero sales fluff.
