继承 ---寄生式继承和寄生组合式继承

寄生式继承

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

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

转载于:https://www.cnblogs.com/sunmarvell/p/8881240.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值