• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

TypeScript类的装饰器2

原作者: [db:作者] 来自: [db:来源] 收藏 邀请
// 最外层是个函数,再返回一个新的函数
function testDecorator(flag: boolean) {
  if (flag) {
    return function (constructor: any) {
      constructor.prototype.getName = () => {
        console.log('dell');
      }
    }
  } else {
    return function (constructor: any) { }
  }
}

// 执行下这个函数,跟上面不包含的效果是一样 的
@testDecorator(true)
class Test{ }

const test = new Test();
(test as any).getName();

 

这个装饰器有一个缺点,就是原型中加了 getName 方法,下面 text. 点不出来 getName 方法,所以接下来解决这个问题
这里的参数是 any 类型不对,这个构造器就是构造函数类型
/**
 * 装饰器
 * @param constructor 
 * (...args: any[]) => {} 这是一个函数,返回一个对象,接收的参数是任意个,任意类型组成的数组
 * new 代表这是一个构造函数
 */
// function testDecorator<T extends new (...args: any[]) => {}>(constructor: T) {
//   return class extends constructor{
//     name = 'lee';
//     getName() {
//       return this.name;
//     }
//   }
// }
// class Test{ 
//   name: string;
//   constructor(name: string) {
//     this.name = name;
//   }
// }
// const test = new Test('dell');

/**
 * 这个时候外层 test. 还是点不出来,因为 class Test 下面没有 getName,
 * 而是 testDecorator 里面偷偷装饰的,ts 解析不出来,接下来我们的装饰器要换种写法
 */
function testDecorator() {
  return function <T extends new (...args: any[]) => {}>(constructor: T) {
    return class extends constructor{
      name = 'lee';
      getName() {
        return this.name;
      }
    }
  }
}

/**
 * testDecorator() 返回一个装饰器,返回的装饰器去装饰 class 
 * 这个 class 就有了 getName 这个函数
 */
const Test = testDecorator()(class { 
    name: string;
    constructor(name: string) {
      this.name = name;
    }
  }
)


const test = new Test('dell');
console.log( test.getName() );

 

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
TypeScript入门四:TypeScript的类(class)发布时间:2022-07-18
下一篇:
TypeScript发布时间:2022-07-18
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap