简体   繁体   English

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

[英]when are typescript/js decorators executed

When do decorators get executed? 装饰器何时被执行?

class Person {
    @SomeDecorator
    age
}
  1. When I create an instance of Person 当我创建Person的实例时
  2. When the Person class is parsed 解析Person类时

What about static properties? 静态属性怎么样?

A property decorator executes early - when the class is defined. 属性装饰器早期执行 - 定义类时。 You don't need to construct an instance, or access the property. 您无需构造实例或访问该属性。

Example: this logs age without the Person class even being constructed. 示例:这会记录age而不会构造Person类。 The same applies if the property is static. 如果属性是静态的,则同样适用。

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

class Person {
    @SomeDecorator
    public age: number;
}

If you are after hooking into the get and set actions on the property - that is possible too. 如果您正在追踪物业的获取和设定行动 - 这也是可能的。 Here is an example from a listing in Pro TypeScript (Second Edition) . 以下是Pro TypeScript(第二版)中的列表示例。 It works by wrapping the getter and setter. 它通过包装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();

The output of this listing is: 此列表的输出是:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM