当前位置:网站首页>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()边栏推荐
- PIL库和opencv库
- KubeMeet 报名 | 「边缘原生」线上技术沙龙完整议程公布!
- KubeMeet 报名 | 「边缘原生」线上技术沙龙完整议程公布!
- 第21章 内存管理
- Small application components
- Apache Doris 1.1 特性揭秘:Flink 实时写入如何兼顾高吞吐和低延时
- MarkBERT
- High-speed passive link impedance matching routine
- Embedded Development: Embedded Fundamentals - Software Error Classification
- Security whole configuration does not take effect after the Gateway?
猜你喜欢
随机推荐
为什么你的分布式数据中心需要一个全栈智能运维平台?
7 lines of code crashed station B for 3 hours, but because of "a tricky 0"
31个!Golang常用工具来啦(建议收藏)
低代码三部曲之未来
R语言时间序列数据提取:使用xts包的last函数提取时间序列中最后面10天的数据(last 10 day)
turtle简单教程文档
Win11网络不稳定怎么办?Win11连接wifi频繁掉线的解决方法
swin-transformer初步理解
Low code of the trilogy
First-line big factory software test interview questions and answer analysis, the strongest version of 2022...
Make a file upload progress bar
H265码流RTP封装方式详解
7行代码让B站崩溃3小时,竟因“一个诡计多端的0”
如何实时计算日累计逐单资金流
洪九果品、百果园抢滩港股,卖水果是门好生意吗?
redis学习三redis里的list、set、hash、sorted_set、skiplist
Working for 9 years!
R语言时间序列数据提取:使用xts包的first函数提取时间序列中最前面一个月的数据(first 1 month)
pfSense高可用(HA)功能介绍
AI 通过了图灵测试,科学家反应冷淡:“很棒,但没必要”









