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

  • 相关阅读:
    Django学习过程中遇到的问题
    代理工具WebScarab安装(转载)
    MongoDB安装之window版本的安装
    QT打包
    小工具--串口
    多线程--信号量
    关于多线程
    QQ界面及简单操作实现
    udp通信
    char *p = "abc";char p[] = "abc";两者之间的区别
  • 原文地址:https://www.cnblogs.com/bsyblog/p/6595591.html
Copyright © 2011-2022 走看看