[英]when are typescript/js decorators executed
裝飾器何時被執行?
class Person {
@SomeDecorator
age
}
靜態屬性怎么樣?
屬性裝飾器早期執行 - 定義類時。 您無需構造實例或訪問該屬性。
示例:這會記錄age
而不會構造Person
類。 如果屬性是靜態的,則同樣適用。
function SomeDecorator(a, b) {
console.log(b);
}
class Person {
@SomeDecorator
public age: number;
}
如果您正在追蹤物業的獲取和設定行動 - 這也是可能的。 以下是Pro TypeScript(第二版)中的列表示例。 它通過包裝getter和setter來工作。
function log(target: any, key: string) {
let value = target[key];
// Replacement getter
const getter = function () {
console.log(`Getter for ${key} returned ${value}`);
return value;
};
// Replacement setter
const setter = function (newVal) {
console.log(`Set ${key} to ${newVal}`);
value = newVal;
};
// Replace the property
if (delete this[key]) {
Object.defineProperty(target, key, {
get: getter,
set: setter,
enumerable: true,
configurable: true
});
}
}
class Calculator {
@log
public num: number;
square() {
return this.num * this.num;
}
}
console.log('Construct');
const calc = new Calculator();
console.log('Set');
// Set num to 4
calc.num = 4;
console.log('Get');
// Getter for num returned 4
// Getter for num returned 4
calc.square();
此列表的輸出是:
Construct (manual log)
Set (manual log)
-> Set num to 4
Get (manual log)
-> Getter for num returned 4
-> Getter for num returned 4
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.