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:如果父類中含有同一種方法或屬性,會根據賦值的順序,先賦值的會被覆蓋掉


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM