我有一個方法裝飾器,它只允許執行一次裝飾方法。這個函式運行良好,但是在我的第三個單元測驗中它失敗了,因為它給出了未定義的但應該回傳第一個執行結果。
這是我的裝飾器:
import "reflect-metadata";
const metadataKey = Symbol("initialized");
function once(
target: any,
propertyKey: string,
descriptor: PropertyDescriptor
) {
const method = descriptor.value;
descriptor.value = function (...args) {
const initialized = Reflect.getMetadata(
metadataKey,
target,
propertyKey
);
if (initialized) {
return;
}
Reflect.defineMetadata(metadataKey, true, target, propertyKey);
method.apply(this, args);
};
}
我認為問題出在 if 陳述句的回傳中,它應該回傳一些東西但不知道什么。我玩了一點但沒有成功,這就是為什么我請求你幫助。
這些是單元測驗:
describe('once', () => {
it('should call method once with single argument', () => {
class Test {
data: string;
@once
setData(newData: string) {
this.data = newData;
}
}
const test = new Test();
test.setData('first string');
test.setData('second string');
assert.strictEqual(test.data, 'first string')
});
it('should call method once with multiple arguments', () => {
class Test {
user: {name: string, age: number};
@once
setUser(name: string, age: number) {
this.user = {name, age};
}
}
const test = new Test();
test.setUser('John',22);
test.setUser('Bill',34);
assert.deepStrictEqual(test.user, {name: 'John', age: 22})
});
it('should return always return first execution result', () => {
class Test {
@once
sayHello(name: string) {
return `Hello ${name}!`;
}
}
const test = new Test();
test.sayHello('John');
test.sayHello('Mark');
assert.strictEqual(test.sayHello('new name'), 'Hello John!')
})
});
提前致謝!
uj5u.com熱心網友回復:
這個裝飾器基本上是做記憶的,但是方法呼叫的結果并沒有存盤在任何地方。這就是缺少的。
我的建議是添加另一條名為result或其他內容的元資料:
const meta = Reflect.getMetadata(...);
if (meta?.initialized) return meta.result;
const result = method.apply(this, args);
const newMeta = { initialized: true, result };
Reflect.defineMetadata(metadataKey, newMeta, target, propertyKey);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/409674.html
標籤:
下一篇:基于引數值的打字稿條件擴展
