JavaScript•Classes & OOP
JavaScript Classes (ES6): Constructors, Methods & Private Fields
ES6 classes provide syntactic sugar over prototypal inheritance, supporting constructors, methods, and #private fields.
Syntax
class User {
#secret;
constructor(name) {
this.name = name;
}
}
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| constructor | Method | Called automatically when instantiating new instances. |
| #field | Private Identifier | Hard private property inaccessible outside class. |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing JavaScript locally:
// ES6 Class with Private Fields (#)
class BankAccount {
#balance; // True private field
constructor(owner, initialBalance = 0) {
this.owner = owner;
this.#balance = initialBalance;
}
deposit(amount) {
if (amount > 0) {
this.#balance += amount;
console.log("Deposited $" + amount + ". New Balance: $" + this.#balance);
}
}
getBalance() {
return this.#balance;
}
}
const account = new BankAccount("Alice", 250);
account.deposit(100);
console.log("Owner: ", account.owner);
console.log("Balance:", account.getBalance());Expected Output:
Deposited $100. New Balance: $350 Owner: Alice Balance: 350
How It Works: Step-by-Step
- Line 2: Declares #balance as a private field (cannot be read or written from outside).
- Lines 4-7: Constructor initializes instance properties.
- Lines 9-14: Public deposit method mutates private #balance safely.
Key Concepts
- Classes are blueprints; new ClassName() instantiates an object.
- #privateField provides true language-enforced encapsulation in modern JavaScript.
- Classes are not hoisted; you must declare a class before using it.
Common Mistake: Trying to access private fields outside the class
Accessing #field from outside class scope raises a SyntaxError at compile time.
❌ Incorrect
account.#balance // SyntaxError: Private field '#balance' must be declared in an enclosing class
✅ Correct
account.getBalance() // Access via public getter method
Related JavaScript Tutorials & Compiler
JavaScript Class Inheritance with extends and super()
Derive child classes from parent classes using extends and invoke base logic with super().
JavaScript Functions: Arrow Functions, Parameters, and Rest
Master function declarations, expressions, arrow functions, and rest parameters (...args).
JavaScript Closures and Scope: Lexical Scoping Guide
Understand how closures allow inner functions to retain access to outer function scopes.
JavaScript Online Compiler
Open in Compilra IDE
Run and test JavaScript on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.