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

寄生式继承

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

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


更多专业前端知识,请上 【猿2048】www.mk2048.com

你可能感兴趣的:(前端,前端,js)