Consider a scenario where you need to dynamically modify method arguments using a decorator at runtime. To illustrate this concept, let's simplify it with an example: setting all arguments to "Hello World":
export const SillyArguments = (): MethodDecorator => {
return (
target: Object,
propertyKey: string | symbol,
descriptor: PropertyDescriptor
) => {
const originalMethod = descriptor.value;
descriptor.value = (...args: any[]) => {
Object.keys(args).forEach(i => {
args[i] = 'Hello World';
});
return originalMethod.apply(null, args);
};
return descriptor;
}
};
Here is how you can use this decorator:
class TestClass {
private qux = 'qux';
@SillyArguments()
foo(val: any) {
console.log(val);
console.log(this.qux);
this.bar();
}
bar() {
console.log('bar');
}
}
const test = new TestClass();
test.foo('Ciao mondo'); // prints "Hello World"
TypeError: Cannot read property 'qux' of null
The issue arises from apply(null, args)
, which changes the context of this
. Thus, accessing the instance variable qux
within foo()
becomes impossible.
One option is to modify the call to
originalMethod.apply(target, args)
, but in this case, qux
is undefined when invoking foo()
.
Is there a way to execute originalMethod
with the correct context of this
set to the instance?