Mixins混入
一、对象混入 合并
当我们有两个或多个对象的时候,如何将这两个对象合并,如图:
interface A {
name:string
}
interface B {
age:number
}
let a:A = {
name:'小明'
}
let b:B = {
age:10
}
// 1.扩展运算符 浅拷贝 返回新的类型
let c = {...a,...b}
// 2.ES6 Object.assign 浅拷贝 交叉类型
let c2 = Object.assign({},a,b)
二、类的混入
// 插件类型的混入
class Logger {
log(msg:string){
console.log(msg)
}
}
class Html {
render(){
console.log('render')
}
}
class App {
run(){
console.log('run')
}
}
type Custructor<T> = new (...args:any[]) => T
function pluginMinxins <T extends Custructor<App>>(Base:T){
return class extends Base {
private Logger = new Logger()
private Html = new Html()
constructor(...args:any[]){
super(...args)
this.Logger = new Logger()
this.Html = new Html()
}
run () {
this.Logger.log('run')
}
render(){
this.Logger.log('run')
this.Html.render()
}
}
}
const mixins = pluginMinxins(App)
const app = new mixins()
app.run()
app.render()