继承---寄生式继承
寄生式继承是与原型式继承紧密相关的一种思路。其思路与寄生构造函数和工厂模式类似,即创建一个仅用于封装继承过程的函数
该函数在内部以某种方式来增强对象,最后再像真的是它做了所有工作一样返回对象。寄生式模式如下例1所示:
例1:
function createAnother(original){
var clone=Object(original); //通过调用函数创建一个新对象
clone.sayHi=function(){ //以某种方式来增强这个对象
alert("hi");
};
return clone; //返回这个对象
}
var person={
name:"Tom",
friends:["111","222","333"]
}
var anotherPerson=createAnother(person);
anotherPerson.sayHi(); //hi
alert(anotherPerson.friends); //111,222,333
在例1中,基于person对象返回了一个新对象anotherPerson。新对象不仅具有person的所有属性和方法,而且还有自己的
sayHi方法。
使用寄生式继承来为对象添加函数,会由于不能做到函数复用而降低效率,这一点与构造函数模式相似。