亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

【十月打卡】第63天 TypeScript(19)

標簽:
Typescript

访问器装饰器

访问器装饰器有3个参数分别是:

  • target:原型
  • key:属性名
  • descriptor: 该属性的描述符

只能在getter或者setter其中一个增加装饰器,不可以同时加

function getNameDecoration(target: any, key: string, descriptor: any) {
  console.log(target, key, descriptor)
}

class Test {
  constructor(private _name: string) {}

  @getNameDecoration
  get name() {
    return this._name;
  }

  set name(val: string) {
    this._name = val;
  }
}

const test = new Test('hello');

console.log(test.name);

属性装饰器

属性装饰器没有descriptor描述符,只有target和key

  • target:原型
  • key:属性名

不能通过target[key]修改实例上的属性,因为target指向原型,修改的是原型上的属性,不是实例的属性。

function getNameDecoration(target: any, key: string) {
  console.log(target, key);
}

class Test {
  @getNameDecoration
  name = 'tz';
}

const test = new Test();
test.name = 'hello';
console.log(test.name);

参数装饰器

参数装饰器可以对静态方法以及原型方法的参数进行处理
不同的是第三个参数是当前参数的索引值

target:静态方法执行类本身;原型方法指向原型
key:方法名(注意:不是参数名)
index: 当前参数的索引值
function paramsDecoration(target: any, key: string, index: number) {
  console.log(target, key, index);
}

class Test {
  static getInfo(@paramsDecoration name: string, age: number) {}

  getInfo(@paramsDecoration name: string, age: number) {}
}

const test = new Test();

装饰器的应用

如下 userInfo如果为undefined,直接调用会报错;
如果单独给每个方法增加 try catch 有些冗余;
装饰器可以应用到此类场景

const userInfo: any = undefined;

function catchError(msg: string) {
  return function (target: any, key: string, descriptor: any) {
    const fn = descriptor.value;

    descriptor.value = function () {
      try {
        fn();
      } catch (e) {
        console.log(`${msg}找不到`);
      }
    };
  };
}

class Test {
  @catchError('name')
  getName() {
    return userInfo.name;
  }
  @catchError('age')
  getAge() {
    return userInfo.age;
  }
}
const test = new Test();
test.getName();
test.getAge();
點擊查看更多內容
TA 點贊

若覺得本文不錯,就分享一下吧!

評論

作者其他優質文章

正在加載中
Web前端工程師
手記
粉絲
3
獲贊與收藏
9

關注作者,訂閱最新文章

閱讀免費教程

  • 推薦
  • 評論
  • 收藏
  • 共同學習,寫下你的評論
感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦
今天注冊有機會得

100積分直接送

付費專欄免費學

大額優惠券免費領

立即參與 放棄機會
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號

舉報

0/150
提交
取消