类里访问器的装饰器

2022-04-19  本文已影响0人  泡杯感冒灵
类的访问器指的就是 getter和setter访问器
function visitDecorator(target: any, key: string,descriptor:PropertyDescriptor) {

};

class Test{
  private _name: string;
  constructor(name: string) {
    this._name = name;
  }
  // getter访问器
  get name() {
    return this._name;
  }
  @visitDecorator
  //  setter访问器
  set name(name:string) {
    this._name = name;
  }
}

const test = new Test('yang');
test.name = '123';
console.log(test.name); //123
function visitDecorator(target: any, key: string,descriptor:PropertyDescriptor) {
  descriptor.writable = false;
};

const test = new Test('yang');
test.name = '1231313';
console.log(test.name); // 报错
注意:getter和setter不能用同名的装饰器
上一篇 下一篇

猜你喜欢

热点阅读