After defining a private member with #
, attempting to redefine a member that utilizes this private member will result in the inability to access it:
class Foo {
#secret = "Keyboard Cat";
method() {
console.log(this.#secret);
}
}
const target = Foo.prototype;
const key = "method";
const desc = Object.getOwnPropertyDescriptor(target, key);
const og = desc.value;
desc.value = function (...args) {
return og.apply(target, args);
};
Object.defineProperty(target, key, desc);
new Foo().method();
Uncaught TypeError: Cannot read private member #secret from an object whose class did not declare it
Why is this happening? I simply wrapped the original method in this case. Keep in mind that this example is a greatly simplified version of using decorators with TypeScript. Is there a way to work around this limitation while still being able to modify and "alter" the method?
Here is the same scenario, but with a TypeScript decorator:
const Curse: MethodDecorator = (target, _, desc) => {
const og = desc.value as Function;
desc.value = function (...args: any[]) {
return og.apply(target, args);
} as any;
return desc;
};
class Foo {
#secret = "Keyboard Cat";
@Curse
method() {
console.log(this.#secret);
}
}
new Foo().method();