zoukankan      html  css  js  c++  java
  • 继承 ---寄生式继承和寄生组合式继承

    寄生式继承

    function obj(o){
      function F(){}
      F.prototype=o;
      return new F();
    }
    function createPerson(orig){
     var thePerson=obj(orig);
      thePerson.sayHi=function(){
        console.log('hi');
        };
      thePerson.sex='female';
        return  thePerson;   
    }
    var person={
    name:"zhangsan",
    age:18,
    friends:['Lisi','wangwu','zhaoliu']
    };
    
    var newPerson=createPerson(person);
    newPerson.sayHi();      //hi
    console.lo           g(newPerson.friends); //["Lisi", "wangwu", "zhaoliu"]
    console.log(newPerson.sex);   //female

    函数不能复用,降低效率,但新对象不仅具有person的属性和方法,还有自己的方法。

    寄生组合式继承

    function obj(o){
      function F(){}
      F.prototype=o;
      return new F();
    }
    function inheritPro(subType,superType){
      var pro=obj(superType.prototype);
      pro.constructor=subType;
      subType.prototype=pro;
    }
    
    function SuperType(name){
      this.name=name;
      this.friends=['Lisi','wangwu','zhaoliu'];
    }
    SuperType.prototype.sayName=function(){
       console.log(this.name);
    };
    function SubType(name,age){
       SuperType.call(this,name);
       this.age=age;
    };
    inheritPro(SubType,SuperType);
    var thePerson=new SubType('sunmenghua',24);
    console.log(thePerson.age); //24
    console.log(thePerson.friends)
    // ["Lisi", "wangwu", "zhaoliu"]

     计生组合式继承是引用类型最理想的继承

  • 相关阅读:
    eclipse
    7lession-基础数据使用介绍
    6lession-基本数据类型
    监听复选框
    arttemplate02
    最后判断权重总分
    ajax
    屏幕尺寸发生变化时页面自适应
    js获取url中的中文参数出现乱码
    js 为什么计算结果老是出现NaN
  • 原文地址:https://www.cnblogs.com/sunmarvell/p/8881240.html
Copyright © 2011-2022 走看看