phymooc / learn-typescript

0 stars 0 forks source link

Decorator 装饰器 #2

Open phymo opened 2 years ago

phymo commented 2 years ago

tsconfig.json 需要配置 "experimentalDecorators": true

  • 能够被附加到类声明,方法, 访问符,属性或参数上,
phymo commented 2 years ago

类声明 装饰器

// 装饰器函数 sealed, 接受类的constructor函数
function sealed(constructor: Function) {
  console.log('sealed');
 //  Object.seal 封闭一个对象 不可配置
  Object.seal(constructor);
  Object.seal(constructor.prototype);
}

@sealed
class Greeter {
  greeting: string;
  constructor(message: string) {
    this.greeting = message;
  greatting() {
     return 'hello' + this.greeting;
  }
}
phymo commented 2 years ago

方法 装饰器

function enumerable(value: boolean) {
   // 注意返回的装饰器函数的三个参数
    return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
        descriptor.enumerable = value;
    };
}

class Greeter {
    greeting: string;
    constructor(message: string) {
        this.greeting = message;
    }

    @enumerable(false)
    greet() {
        return "Hello, " + this.greeting;
    }
}