[英]I'm having a problem with method decorators and class decorators
我有一個類裝飾器,該類裝飾器更改了類並在其中添加了一個屬性。 然后,我有一個方法裝飾器,該裝飾器位於具有該類裝飾器的類中,並且方法裝飾器正在嘗試訪問由另一個裝飾器創建的類中的屬性。
// The Class Decorator
export function SomeDecorator(): ClassDecorator {
return target => {
target['property'] = { text: 'some text' };
return target;
}
}
// The Method Decorator
export function SomeOtherDecorator(): MethodDecorator {
return (target, propertyKey: string, propertyDescriptor: PropertyDescriptor) => {
console.log(target['property'].text);
}
}
// The Class
@SomeDecorator()
export class SomeClass {
@SomeOtherDecorator()
someMethod() {}
}
它將在運行時對此進行回答:TypeError:無法讀取未定義的屬性'text'
為什么?
就像Titian所說的那樣,類裝飾器在方法裝飾器之后運行,這就是示例代碼console.log(target['property'].text);
失敗。
不確定您的實際用例,但是如果您可以推遲對target['property']
的訪問,則不會有任何問題。
function SomeOtherDecorator(): MethodDecorator {
return (target, propertyKey: string, propertyDescriptor: PropertyDescriptor) => {
const fn = descriptor.value;
// no problem, because `target['property']` is only accessed
// when the decorated method (not decorator) is called.
descriptor.value = (...args) => {
console.log(target['property'].text);
return fn.apply(target, args);
};
}
}
您甚至可以使用getter來惰性運行裝飾器,應注意大多數用例。
function SomeOtherDecorator(): MethodDecorator {
return (target, propertyKey: string, propertyDescriptor: PropertyDescriptor) => {
const fn = descriptor.value;
let decoratedFn;
descriptor.get = () => {
if (decoratedFn) return decoratedFn;
// do whatever you want to decorate the method/fn
// including access to `target['property']`
decoratedFn = ...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.