【发布时间】:2020-06-08 00:07:30
【问题描述】:
我正在为以下类方法编写装饰器:
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 现在未定义。我猜这是因为从技术上讲,该方法是从类的上下文之外调用的。
我的设计是否存在缺陷,或者这是我应该预料到的?如果是这样,我有办法在仍然使用装饰器的同时保留上下文吗?
【问题讨论】:
标签: node.js typescript oop decorator