javascript继承学习系列之四:组合继承(Combination Inheritance)

    它结合了原型链和对象伪装各自优点的方式。它的基本思路是使用原型链继承原型上的属性和方法,使用对象伪装继承实例属性。通过定义原型方法,允许函数复用,并允许每个实例拥有它们自己的属性。参考以下代码:
function BaseClass(name)
{
   this.name = name;
   this.colors = ["red","blue"];
}
BaseClass.prototype.getName = function(){return this.name;}

function ChildClass(name,age)
{
   // inherit
   BaseClass.call(this,name);
   this.age = age;
}
// inherit
ChildClass.prototype = new BaseClass();

ChildClass.prototype.getAge = function(){return this.age;}

var instance1 = new ChildClass("sds1",28);
var instance2 = new ChildClass("sds2",29);
instance2.colors.push("green");
var instance3 = new ChildClass("sds3",30);

alert(instance1.colors);//red,blue
alert(instance1.getName());//sds1
alert(instance1.getAge());//28

alert(instance2.colors);//red,blue,green
alert(instance2.getName());//sds2
alert(instance2.getAge());//29

alert(instance3.colors);//red,blue
alert(instance3.getName());//sds3
alert(instance3.getAge());//30

     原型链和对象伪装的继承,它们各自有优缺点,并且是互补的,而组合继承正是利用了它们的这种互补性将其结合在一起,比较完美的实现了继承。通过上面的示 例,清楚的看到同时通过组合的方式ChildClass继承了BaseClass类,ChildClass类的三个实例的属性各不影响,且方法都是可复用 的原型方法。
    组合继承的本质还是原型链和对象伪装。
posted @ 2011-07-06 13:28  沈沈  阅读(232)  评论(0编辑  收藏  举报