When I intentionally make "this" of a method as undefined using a high order function and try to access the private method in the function(presented below as 'deprivedMethod2'), the error message is quite weird.
expected message: Uncaught TypeError: Cannot read properties of undefined (reading '#privateMethod')
actual message: Uncaught TypeError: Cannot read properties of undefined (reading 'TestClass')
Below is how to reproduce the situation.
class TestClass {
publicWithPublic() {
this.publicMethod();
}
publicWithPrivate() {
this.#privateMethod();
}
publicMethod() {
console.log('public');
}
#privateMethod() {
console.log('private');
}
}
// function to unbind this
const depriveThis = (func) => () => func();
const obj = new TestClass();
const deprivedMethod1 = depriveThis(obj.publicWithPublic)
const deprivedMethod2 = depriveThis(obj.publicWithPrivate);
deprivedMethod1();
// Uncaught TypeError: Cannot read properties of undefined (reading 'publicMethod')
deprivedMethod2();
// Uncaught TypeError: Cannot read properties of undefined (reading 'TestClass') => why???
expected message: Uncaught TypeError: Cannot read properties of undefined (reading '#privateMethod')
actual message: Uncaught TypeError: Cannot read properties of undefined (reading 'TestClass')
Here I understood that error occurs because "this" is unbound going through depriveThis function.
However, I could not understand why "reading 'TestClass'" occurs when trying to access privateMethod.
I expected "Reading #privateMethod"!
I wonder how JS knew the function was bound to "TestClass" even after it lost "this" binding.
If you are aware of the slightest hint, please let me know and it will be a big help :)