类里方法的装饰器

2022-04-19  本文已影响0人  泡杯感冒灵
类的方法的装饰器
function getNameDecorator(target: any, key: string,descriptor: PropertyDescriptor) {
  // console.log(target,key);
};

class Test{
  name: string;
  constructor(name: string) {
    this.name = name;
  }
  @getNameDecorator
  getName() {
    return this.name;
  }
  // static getName() {
  //   return '123';
  // }
}

// const test = new Test('yang');
// console.log(test.getName());
descriptor参数就是对方法的 PropertyDescriptor属性(value,enumerable,configurable,writable )做一些编辑
class Test{
  name: string;
  constructor(name: string) {
    this.name = name;
  }
  @getNameDecorator
  getName() {
    return this.name;
  }
}

// 默认情况下 descriptor的writable为true,也就是可以被修改。false时是只读的
const test = new Test('yang');
test.getName = () => {
  return '123';
}

console.log(test.getName());  // 123
function getNameDecorator(target: any, key: string,descriptor:PropertyDescriptor) {
  // console.log(target,key);
  descriptor.writable = false;
  descriptor.value = function () {
    return 'decorator'
  }
};

class Test{
  name: string;
  constructor(name: string) {
    this.name = name;
  }
  @getNameDecorator
  getName() {
    return this.name;
  }
}

const test = new Test('yang');
console.log(test.getName());  // decorator
上一篇 下一篇

猜你喜欢

热点阅读