Course contentsShow
← JavaScript
Lesson 1989 of 2,72341. Modern JavaScript Features (ES2020+)Free lesson

Accessing Private Fields from Within

How private fields work across instances of the same class and access patterns.

Accessing Private Fields from Within

You'll learn how private fields work when one instance of a class interacts with another instance of the same class.

The Surprising Truth About Private Access

Here's something that trips up many developers: private fields aren't just accessible within the current instance (this). They're accessible across all instances of the same class within that class's methods.

Think of it like a family secret. All members of the Smith family know the secret, even when they're talking about another Smith family member. The privacy is about keeping outsiders away, not family members apart.

How Cross-Instance Access Works

class BankAccount {
  #balance;

  constructor(initialBalance) {
    this.#balance = initialBalance;
  }

  canTransferTo(otherAccount, amount) {
    // I can access MY private field
    if (this.#balance < amount) return false;

    // I can ALSO access the OTHER account's private field!
    // Both are BankAccount instances
    return otherAccount.#balance >= 0;
  }

  transferTo(otherAccount, amount) {
    this.#balance -= amount;
    otherAccount.#balance += amount; // Access other's private field
  }
}

const account1 = new BankAccount(100);
const account2 = new BankAccount(50);

account1.transferTo(account2, 30); // Works! Both private fields accessible

Notice how transferTo can modify both this.#balance and otherAccount.#balance. The privacy boundary is the class, not the individual instance.

Why This Matters

This design enables methods like comparison, copying, or merging operations where one instance needs to inspect or modify another's private state—without breaking encapsulation.

Key Takeaway: Private fields are accessible to any method of the class, even when operating on other instances of the same class—privacy is enforced at the class boundary, not the instance boundary.