Accessing Private Fields in Methods
You'll learn how to read and modify private fields from within instance and static methods using the # syntax.
The Core Idea
Private fields (declared with #) aren't accessible outside the class body, but they work perfectly inside instance and static methods. You simply reference them with the # prefix, just as you declared them. This is how your class encapsulates data—keeping it hidden from external code while giving your methods full access to work with it.
Think of it like a lockbox: only methods that "live inside" the class have the key (#) to open and use the private contents.
How It Works
Instance methods can access private instance fields directly:
class BankAccount {
#balance = 0;
deposit(amount) {
this.#balance += amount; // Reading and modifying private field
}
getBalance() {
return this.#balance; // Reading private field
}
}
const account = new BankAccount();
account.deposit(100);
console.log(account.getBalance()); // 100
Static methods can access private static fields:
class Counter {
static #count = 0;
static increment() {
this.#count++; // Accessing private static field
}
static getCount() {
return this.#count;
}
}
Counter.increment();
console.log(Counter.getCount()); // 1
Notice that you always use this.#fieldName in instance methods and this.#fieldName (or ClassName.#fieldName) in static methods.
Key Takeaway: Private fields are fully accessible within all methods of the class using the # syntax—this is where encapsulation happens, allowing controlled access to hidden data.