TypeScript 访问器装饰器

访问器譬如 private public protect
 
/**
 * 访问器装饰器的参数跟方法装饰器的参数是一样的
 * @param target  prototype
 * @param key function name
 * @param descriptor 描述符
 */
function visitDecorator(target: any, key: string, descriptor: PropertyDescriptor) {
  descriptor.writable = false;
}

class Test{ 
  private _name: string;
  constructor(name: string) {
    this._name = name;
  }
  get name() {
    return this._name
  }
  @visitDecorator
  set name(name: string) {
    this._name = name;
  }
}

const test = new Test('dell');
test.name = '11222222';
console.log(test.name);
// 访问器装饰器将 writable 为 false 也是会报错的,因为这不能重写

 

posted @ 2020-08-07 08:22  wzndkj  阅读(430)  评论(0编辑  收藏  举报