0

我正在玩 Typescript 装饰器,当我实例化一个类时,一切都很好。使用以下代码,我的 Class-decorator 被调用: import { MyClass } from "./MyClass"; const myClass = new MyClass(); 但是当我不像上面的示例那样显式地实例化类时,不会调用任何装饰器。例如,这个模块:https ://github.com/xrobert35/es-mapping-ts就依赖这样的结构将所有类保存在一个存储中并生成一个映射。我在没有先实例化类并生成映射的情况下尝试了它,但它也不起作用。在实例化放置装饰器的类之前,是否必须设置任何 Webpack 或 Typescript 配置才能执行装饰器?在我的知识状态和一些在线教程中,定义了在定义类时调用类装饰器,而不是在实例化类时调用。干杯!

4

1 回答 1

1

你可以用类级别的装饰器替换原来的类构造器来做各种很酷的事情:

function example(target: any) {
    // save a reference to the original constructor
    const original = target;

    // the new constructor behaviour
    const f: any = function (...args: any[]) {
        console.log("Hook before original constructor...");

        const newArgs = [...args].reverse();

        const instance = new original(...newArgs);

        console.log("Hook after original constructor...");

        instance.d = 'ddd';

        return instance;
    }

    // copy prototype so intanceof operator still works
    f.prototype = original.prototype;

    // return new constructor (will override original)
    return f;
}

@example
class SomeClass {
    constructor(public a: number, public b: number, public c: number) {
        console.log("Hello from constructor!")
    }
}

const instance1 = new SomeClass(1, 2, 3);
console.log(instance1); // SomeClass {a: 3, b: 2, c: 1, d: "ddd"}

链接到游乐场

于 2020-02-16T20:08:51.670 回答