My understanding is that private methods are not part of the prototype chain, and therefore, are not inherited by subclasses. However, I am confused about how instances of a class access private methods when those methods are invoked through public methods of the class.
class MyClass {
#privateMethod() {
return 'I am a private method';
}
publicMethod() {
return this.#privateMethod(); // Access private method from within the class
}
}
const instance = new MyClass();
console.log(instance.publicMethod()); // Logs: I am a private method
When instance.publicMethod()
is called, this
inside publicMethod
refers to instance
. Since private methods are not part of the instance itself or the prototype chain, how does this.#privateMethod()
work? How does the private method get accessed even though the instance doesn’t directly contain the private method?