装饰器介绍

TypeScript 项目开启装饰器

{
"compilerOptions": {
 "target": "ES5",
 "experimentalDecorators": true
 }
}

装饰器的分类

按照装饰器的写法划分

function sealed(target) {
    // do something with "target" ...
}

实际上是普通装饰器写法的柯里化处理

function color(value: string) { // 这是一个装饰器工厂
    return function (target) { //  这是装饰器
        // do something with "target" and "value"...
    }
}

安装装饰器的放置方法划分

- 类装饰器

传入一个属性:constructor 构造函数

意味着可以改变类的构造器


function sealed(constructor: Function) {
    Object.seal(constructor);
    Object.seal(constructor.prototype);
}

@sealed
class Greeter {
    greeting: string;
    constructor(message: string) {
        this.greeting = message;
    }
    greet() {
        return "Hello, " + this.greeting;
    }
}

- 属性装饰器