假设您必须使用装饰器在运行时更改方法参数。一个简单的例子:所有参数都设置为“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;
}
};
使用示例:
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
这里的问题是apply(null, args)
,它改变了this
的上下文。这使得无法从 foo()
内部调用名为 qux
的实例变量。
另一种可能性是将调用更改为originalMethod.apply(target, args)
,但这次qux
是undefined
,而bar()
可以被调用。
是否有可能在将 this
上下文正确设置为实例的情况下调用 originalMethod
?
最佳答案
使用 function
函数而不是箭头函数,以便您接收原始 this
上下文并可以将其传递:
export const SillyArguments = (): MethodDecorator => {
return (
target: Object,
propertyKey: string | symbol,
descriptor: PropertyDescriptor
) => {
const originalMethod = descriptor.value;
descriptor.value = function (...args: any[]) {
Object.keys(args).forEach(i => {
args[i] = 'Hello World';
});
return originalMethod.apply(this, args);
};
return descriptor;
}
};
关于javascript - 使用 MethodDecorator 更改函数的参数,而不更改 "this value"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52105906/