zoukankan      html  css  js  c++  java
  • Javascript继承6:终极继承者----寄生组合式继承

    /*
    * 寄生式继承依托于原型继承,原型继承又与类式继承想象。
    * 即: 原型与构造函数的组合继承
    * 寄生式继承  继承原型
    * 传递参数 childClass 子类
    * 传递参数 parentClass 父类
    */
    
    //原型式继承
    function inheritObj(obj){
        //声明一个过渡函数对象
        function F(){}
        //过渡对象的原型继承父对象
        F.prototype = obj;
        //返回过渡对象的一个实例,该实例的原型继承了父对象
        return new F();
    }
    
    function inheritPrototype(childClass,parentClass){
        //复制一份父类原型副本保存在变量中
        var p = inheritObj(parentClass.prototype);
        //修正因为重写子类原型导致子类的constructor属性被修改
        p.constructor = childClass;
        //设置子类原型
        childClass.prototype = p;
    }
    
    // 定义父类
    function ParentClass(name){
        this.name = name;
        this.books = ['Html'];
    }
    //定义父类原型方法
    ParentClass.prototype.getName = function(){
        console.log(this.name);
    }
    //定义子类
    function ChildClass(name,time){
        //构造函数是继承
        ParentClass.call(this,name);
        //子类新增属性
        this.time = time;
    }
    
    // 寄生式继承父类原型
    inheritPrototype(ChildClass,ParentClass);
    //子类新增方法
    ChildClass.prototype.getTime = function(){
        console.log(this.time);
    }
    // test
    var child1 = new ChildClass('react',2018);
    var child2 = new ChildClass('vue',2017);
    
    child1.books.push('css');
    
    console.log(child1.books)     // ['Html','css']
    console.log(child2.books)     // ['html']
    
    child2.getName()              // Vue
    child2.getTime()              // 2017

    设计模式中的经典笔录

  • 相关阅读:
    生成验证码图片(含模糊背景)
    再论验证码安全:请及时销毁你的验证码
    C# DES 加密/解密
    jQuery 表格工具集
    见证VS2010发布会[转]
    jQuery Lightbox(balupton版)图片展示插件讲解
    Coding完美世界——VS2010发布会见闻!【转】
    asp.net对Get请求的加密
    【C#源码】DES加密解密类
    asp.net1.1和asp.net 2.0共存
  • 原文地址:https://www.cnblogs.com/-walker/p/9737602.html
Copyright © 2011-2022 走看看