//混合多个类为一个类
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()
Typescript类功能混合(mixin)使用,将多个类中功能合并到一个对象
原创文章标签 typescript javascript 开发语言 原型对象 构造函数 文章分类 TypeScript 前端开发
©著作权归作者所有:来自51CTO博客作者编程汇也的原创作品,请联系作者获取转载授权,否则将追究法律责任
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
手写一个拖拽文件功能
手写一个拖拽文件功能
Nodejs JavaScript -
如何将多个Excel合并到一个Excel中?
今天遇到这么一个问题,需要将多个Excel表格中的数据汇总表,合并在一个Excel中,并且显示一致。因此编写了以下代码来解决这个
Excel 合并表格 excel表格 数据 f5 -
Word——将多个Word文档内容合并到一个文档中
Word——将多个Word文档内容合并到一个文档中
Word office 合并文件 -
java将多个文件的内容合并到一个文件中
运用java语法中的IO操作,将指定多个文件的内容写入
java jvm 开发语言 System 目标文件