Example 1 — Outside access throws
Syntax/runtime barrier.
JavaScript
class A { #x = 1; }
const a = new A();
try { console.log(a.#x); } catch (e) { console.log("blocked"); } How It Works
- Cannot access #x outside class (parse/runtime).
Fields and methods starting with # are private to the class body. Outside code cannot read or write them—even on the same object.
class Wallet {
#balance = 0;
deposit(n) { this.#balance += n; }
getBalance() { return this.#balance; }
}
const w = new Wallet();
w.deposit(10);
console.log(w.getBalance()); Syntax/runtime barrier.
class A { #x = 1; }
const a = new A();
try { console.log(a.#x); } catch (e) { console.log("blocked"); } #helper() stays internal.
class A { #h(){ return 1; } out(){ return this.#h(); } }
console.log(new A().out()); Each class has its own # names.
console.log("private to declaring class"); CODETOFUN NEWS
Get the latest IT news, programming updates, and technology trends directly on your phone.
Your daily dose of tech, straight to your feed.
6 people found this page helpful