1 回答
TA贡献1815条经验 获得超13个赞
这可以通过覆盖类方法来实现
function AttachToAllClassDecorator<T>(someParam: string) {
return function(target: new (...params: any[]) => T) {
for (const key of Object.getOwnPropertyNames(target.prototype)) {
// maybe blacklist methods here
let descriptor = Object.getOwnPropertyDescriptor(target.prototype, key);
if (descriptor) {
descriptor = someDecorator(someParam)(key, descriptor);
Object.defineProperty(target.prototype, key, descriptor);
}
}
}
}
基本上遍历所有方法(可能围绕它添加一些逻辑以将某些方法列入白名单/黑名单)并用包装了方法装饰器的新方法覆盖。
这是方法装饰器的基本示例。
function someDecorator(someParam: string): (methodName: string, descriptor: PropertyDescriptor) => PropertyDescriptor {
return (methodName: string, descriptor: PropertyDescriptor): PropertyDescriptor => {
let method = descriptor.value;
descriptor.value = function(...args: any[]) {
console.warn(`Here for descriptor ${methodName} with param ${someParam}`);
return method.apply(this, args);
}
return descriptor;
}
}
添加回答
举报