什么时候执行typescript / js装饰器

时间:2017-11-28 20:25:18

标签: javascript typescript decorator

装饰器何时被执行?

class Person {
    @SomeDecorator
    age
}
  1. 当我创建Person的实例时
  2. 解析Person类时
  3. 静态属性怎么样?

1 个答案:

答案 0 :(得分:2)

属性装饰器早期执行 - 定义类时。您不需要构建实例或访问该属性。

示例:即使构建了age类,也会记录Person。如果属性是静态的,则同样适用。

function SomeDecorator(a, b) {
    console.log(b);
}

class Person {
    @SomeDecorator
    public age: number;
}

如果您正在追踪对物业的获取和设定行动 - 这也是可能的。以下是Pro TypeScript (Second Edition)中的商家信息示例。它通过包装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