zoukankan      html  css  js  c++  java
  • 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:如果父类中含有同一种方法或属性,会根据赋值的顺序,先赋值的会被覆盖掉

  • 相关阅读:
    继承
    构造函数,重载
    Java Scanner学习记录
    20131204-数据库基础
    20131128-正则表达式与委托
    20131125-序列化与正则表达式
    20131127-正则表达式
    20131120-接口字符串-小鸭子练习
    20131118-静态类抽象类-外部设备
    20131117-练习面向对象
  • 原文地址:https://www.cnblogs.com/bsyblog/p/6595591.html
Copyright © 2011-2022 走看看