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