我正在为下面的类方法编写装饰器:
export default class API {
...
public async request(url_stub: string, options: any = {}): Promise<any> {
console.log(this)
const url = this.join_url(url_stub);
...
}
}当未应用装饰器时,函数按预期运行,但当我应用以下装饰器之一时:
export function log_func(_target: any,
name: string,
descriptor: PropertyDescriptor): PropertyDescriptor {
const original_function = descriptor.value;
descriptor.value = (... args: any[]) => {
const parameters = args.map((a) => JSON.stringify(a)).join();
const result = original_function.apply(this, args);
const result_str = JSON.stringify(result);
console.log(`Call: ${name}(${parameters}) => ${result_str}`);
return result;
}
return descriptor;
}export function uri_encode(parameter_index?: number) {
return (_target: any,
name: string,
descriptor: PropertyDescriptor): PropertyDescriptor => {
const original_function = descriptor.value;
descriptor.value = (... args: any[]) => {
args = args.map((arg, index) => {
if (parameter_index === undefined || index === parameter_index) {
arg = encodeURI(arg);
}
return arg;
});
const result = original_function.apply(this, args);
return result;
}
return descriptor;
}
}因此:
@uri_encode(0)
@log_func
public async request(url_stub: string, options: any = {}): Promise<any> {类方法中的this现在未定义。我猜这是因为从技术上讲,该方法是从类的上下文外部调用的。
是我的设计中有缺陷,还是这是我应该预料到的?如果是这样的话,有没有办法让我在使用装饰器的同时保留上下文?
发布于 2020-06-08 08:48:32
问题出在我的装饰器上。显然,用() => {}函数修改原始描述符值是个问题。将其更改为function () {}可以使其正常工作。
天知道为什么。
https://stackoverflow.com/questions/62253212
复制相似问题