手寫方法裝飾器(MethodDecorator)

angular中裝飾器:https://www.jianshu.com/p/650023b6a62c

手寫一個方法裝飾器:

export class AppComponent implements OnInit {
  ngOnInit() {
    new Person().pay(100);
  }
}
function methodName(target: any, key: string, descriptor: PropertyDescriptor) {
  const origin = descriptor.value;
  descriptor.value = function delegate() {
    const className = target.constructor.name;
    const args = JSON.stringify(arguments);
    console.log(`${className}.${key}.${args}`);
    return origin.call(this, ...arguments);
  };
}

class Person {
  @methodName
  pay(money) {
    console.log(money);
  }
}

打印結果:

 key值:pay,表示方法名

target打印結果:

descriptor: 

descriptor.PropertyDescriptor: 

將他保存下來,賦值給origin

arguments:

this指 ,將pay方法重新綁定到這個類上。

設置pay方法無法重寫,則可以寫一個只讀裝飾器:

export class AppComponent implements OnInit {
  title = 'codeTest';
  ngOnInit() {
    // tslint:disable-next-line:only-arrow-functions
    new Person().pay = function () {

    }
  }
}

function readyOnly(target: any, key: string, descriptor: PropertyDescriptor) {
  descriptor.writable = false;
}
class Person {
  @readyOnly
  pay(money) {
    console.log(money);
  }
}

 在覆蓋方法的時候,會報錯:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章