ts之 Mixin混入
对象的混入
interface Name {
name : string;
}
interface Age {
age : number;
}
interface Sex {
sex : number;
}
let aa : Name = { name : "ppp" } ;
let bb : Age = { age : 10 } ;
let cc : Sex = { sex : 1 } ;
let obj = Object. assign ( aa, bb, cc) ;
类的混入
class AA {
type : boolean;
changeType ( ) {
this . type = ! this . type;
}
constructor ( type : boolean) {
this . type = type;
}
}
class BB {
name : string;
public changeName ( name: string) : string {
return this . name = name;
}
constructor ( name : string) {
this . name = name;
}
}
class CC implements AA , BB {
type : boolean = false ;
name : string = "ppp" ;
changeType : ( ) => void ;
changeName : ( name : string) => string;
}
mixins ( CC , [ AA , BB ] ) ;
function mixins ( curCls : any, itemCls : any[ ] ) {
itemCls. forEach ( ( item ) => {
Object. getOwnPropertyNames ( item. prototype) . forEach ( ( name ) => {
curCls. prototype[ name] = item. prototype[ name] ;
} ) ;
} ) ;
}
let ccc = new CC ( ) ;
console. log ( "ccc" , ccc. name) ;
console. log ( "ccc" , ccc. type) ;
ccc. changeType ( ) ;
console. log ( "ccc" , ccc. type) ;
ccc. changeName ( "小小" ) ;
console. log ( "ccc" , ccc. name) ;