当前位置:网站首页>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()边栏推荐
猜你喜欢
随机推荐
exdark数据集转yolo格式(仅供参考)
单核浏览器和双核浏览器有什么区别,哪个好用?
Neo4j开源NoSQL数据库
PromptBERT: Improving BERT Sentence Embeddings with Prompts
ECCV 2022 | AirDet:无需微调的小样本目标检测方法
嵌入式开发:嵌入式基础——软件错误分类
我用两行代码实现了一个数据库!
EasyNVR更新版本至(V5.3.0)后页面不显示通道配置该如何解决?
《STL 源码剖析》学习笔记之容器(二)list
Make a file upload progress bar
开源数据标注工具
2022/7/27
优雅实现经典的生产者消费者模式
RestTemplate源码debug:可变形参引发的问题
无人驾驶与人工驾驶的对比,人工驾驶的优缺点
五种常见IO模型
【中标麒麟系统Your trial is EXPIRED and no VALID licens 关闭弹窗】
First-line big factory software test interview questions and answer analysis, the strongest version of 2022...
centos7服务器安全策略
转载:同班毕业两夫妻退休待遇四比一





![Chapter 01 Installation and use of MySQL under Linux [1. MySQL Architecture] [MySQL Advanced]](/img/f6/8c513ab62c8d3259c9c8ef13887276.png)



