当前位置:网站首页>Typescript类功能混合(mixin)使用,将多个类中功能合并到一个对象
Typescript类功能混合(mixin)使用,将多个类中功能合并到一个对象
2022-07-29 18:45:00 【RemoteDev】
//混合多个类为一个类
function MixinFunc(...mixins){
class MixClass{}
for (let m of mixins) {
cloneProto(MixClass,m);//克隆构造函数
cloneProto(MixClass.prototype,m.prototype);//克隆原型对象
}
return MixClass;
}
//克隆对象
function cloneProto(t,s){
for (let k of Reflect.ownKeys(s)) {
//不克隆构造函数key,原型对象key及对象名key
if (k !== 'constructor' && k !== 'prototype' && k !== 'name'){
let d = Object.getOwnPropertyDescriptor(s,k);//取源对象属性描述
Object.defineProperty(t,k,d);//克隆源对象键值对目标对象
}
}
}
class a1{
constructor() {
}
test1(){console.log('a1类的test1方法');}
}
class a2{
constructor() {
}
test2(){console.log('a2类的test2方法');}
}
class a3{
constructor() {
}
test3(){console.log('a3类的test3方法');}
}
let mixCls =MixinFunc(a1,a2,a3);//混合a1,a2,a3这三个类的功能到mixCls这个对象
console.log(Object.getOwnPropertyNames(mixCls.prototype));//[ 'constructor', 'test1', 'test2', 'test3' ]
//调用,因为类的方法都定义在原型对象上,所以Reflect.get要传入混合对象的原型对象
Reflect.get(mixCls.prototype,'test1')();//test1()
Reflect.get(mixCls.prototype,'test2')();//test2()
Reflect.get(mixCls.prototype,'test3')();//test3()边栏推荐
- FPGA设计8-3线优先编码器与3-8线译码器
- Android 面试黑洞——当我按下 Home 键再切回来,会发生什么?
- R语言时间序列数据提取:使用xts包的first函数提取时间序列中最前面两周的数据(first 2 week)
- EasyNVR更新版本至(V5.3.0)后页面不显示通道配置该如何解决?
- centos7 server security policy
- Security whole configuration does not take effect after the Gateway?
- 牛客网剑指offer刷题练习之重构二叉树
- 新西藏,在云上!
- 31个!Golang常用工具来啦(建议收藏)
- R语言时间序列数据提取:使用xts包的first函数提取时间序列中最前面10天的数据(first 10 day)
猜你喜欢
随机推荐
成都 | 转行软件测试,从零收入到月薪过万,人生迎来新转折...
7行代码让B站崩溃3小时,竟因“一个诡计多端的0”
如何防止订单重复支付?
Small application components
Really touch the fish and lead the teacher: The programmer brother works 10 minutes a day with an annual salary of 570,000. I broke the defense...
H265码流RTP封装方式详解
turtle简单教程文档
AI 通过了图灵测试,科学家反应冷淡:“很棒,但没必要”
7 lines of code crashed station B for 3 hours, but because of "a tricky 0"
KubeMeet 报名 | 「边缘原生」线上技术沙龙完整议程公布!
记录一个相当坑爹的WSL局域网访问问题
关于高考选志愿
关于Image scaleType的属性详解,以及每一个属性的区别
如何实时计算日累计逐单资金流
The backslash \\ in MySQL is really a pit
从零在AutoDL调试一份目标检测代码
31个!Golang常用工具来啦(建议收藏)
我用两行代码实现了一个数据库!
项目分析(三个小众的嵌入式产品)
第21章 内存管理








![[数学]必备基本知识](/img/ac/f3552ef31948e1c31ce692fa87a796.png)