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"]

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

  • 相关阅读:
    浅析http缓存
    多级路由请求js文件路径不对的解决方法
    移动端屏幕适配原理以及方法讲解
    zoom与scale的异同
    querySelectorAll选择器的js实现
    垂直居中效果汇总
    windows配置php开发环境
    CentOS 6.2安装nagios
    Ganglia安装
    Ubuntu 14.04上安装Riak
  • 原文地址:https://www.cnblogs.com/sunmarvell/p/8881240.html
Copyright © 2011-2022 走看看