继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

【九月打卡】第11天 TypeScript学习 10-13章

暮雩
关注TA
已关注
手记 65
粉丝 9
获赞 5

课程名称: 晋级TypeScript高手,成为抢手的前端开发人才

课程章节: 10-13 【方法装饰器】方法装饰器的实现

课程讲师: keviny79

课程内容:
方法装饰器使用:
1.不带参数的"方法装饰器"写法

// 声明没有参数的方法装饰器
function MyMethodDecorator(
  targetClassPrototype: any,
  key: string,
  methodDecri: PropertyDescriptor
) {
  console.log("targetClassPrototype:", targetClassPrototype); //
  console.log("key:", key);
  console.log("methodDecri:", methodDecri);
  methodDecri.value();
}

class RoleService {
  public roleName: string = "管理员";
  constructor() {}
  
  // 直接在方法上使用 @ + 参数器名称
  @MyMethodDecorator
  DistribRoles() {
    // 分配角色
    console.log("分配角色.....");
  }
}

2.带参数的"方法装饰器"写法:

// 声明带参数的方法装饰器
function MyMethodDecorator(methodPath: string) {
  return function (
    targetClassPrototype: any,
    key: string,
    methodDecri: PropertyDescriptor
  ) {
    // 使用外界传递参数
    console.log("methodPath:", methodPath);

    console.log("targetClassPrototype:", targetClassPrototype); //
    console.log("key:", key);
    console.log("methodDecri:", methodDecri);
    methodDecri.value();
  };
}

class RoleService {
  public roleName: string = "管理员";
  constructor() {}

  // 直接在方法上使用 @ + 参数器名称 + ([...参数])
  @MyMethodDecorator("/searchFood")
  DistribRoles() {
    // 分配角色
    console.log("分配角色.....");
  }
}

知道了 “方法装饰器”的写法,发现“类装饰器”可以接收一个参数,“方法装饰器”要接收三个参数,分别是:
targetClassPrototype 参数
这里表示是类的原型对象

key 参数
这里的 key 就是方法名称

methodDecri 参数
methodDecri “数据属性”由 js自带的, 就是控制函数的属性的。有如下这些属性:

 {
    configurable?: boolean;		// 是否能参数
    enumerable?: boolean;		// 是否能使用for in 来循环返回对象的属性
    value?: any;		// 属性的值
    writable?: boolean;	//是否是可写属性
    get?(): any;		//在读取属性时调用的函数,
    set?(v: any): void;		//在写入属性时调用的函数
}

课程收获:
明白“方法装饰器”带参数和不带参数的使用。
明白“方法装饰器”中三个参数的意义
图片描述

打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP