1 回答

TA貢獻(xiàn)1815條經(jīng)驗(yàn) 獲得超13個(gè)贊
這可以通過覆蓋類方法來實(shí)現(xiàn)
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;
}
}
添加回答
舉報(bào)