Typescript 模拟实现 多继承

class Animal{
    eat():void{
        alert("animal eat");
    }
}

class Mamal extends Animal{
    breathe() :void{
        alert("Mamal breathe");
    }
}

class WingedAnimal extends Animal {
    fly() {
        alert("WingedAnimal fly");
    }
}
//模仿实现多继承 的函数方法
function applyMixins(derivedCtor:any,baseCtor:any[]) {
    //遍历父类中的所有的属性,添加到子类的属性中中
    baseCtor.forEach(baseCtor => {
        //获取遍历到的父类中的所有属性
        Object.getOwnPropertyNames(baseCtor.prototype).forEach(name => {
            if (name !== "constructor") {
                //父类中的属性,添加到子类的属性中
                derivedCtor.prototype[name] = baseCtor.prototype[name];
            }
        });
    });
} 
//定义Bat类,
class Bat implements Mamal, WingedAnimal{
    fly: () => void;
    breathe: () => void;
    eat: () => void;//这个属性是访问不到
}

applyMixins(Bat, [Mamal, WingedAnimal]);
var bat = new Bat();
bat.fly();
bat.breathe();
bat.eat();//执行无结果,eat是Animal类的

 缺点:
 1:只能在继承一级的方法和属性

 2:如果父类中含有同一种方法或属性,会根据赋值的顺序,先赋值的会被覆盖掉

原文地址:https://www.cnblogs.com/bsyblog/p/6595591.html