跟小D每日学口语

关于js继承学习系列之四:组合继承(Combination Inheritance)[转]

    有时也会被叫做伪经典继承(pseudoclassical inheritance),它是结合了原型链和对象伪装各自优点的方式。它的基本思路是使用原型链继承原型上的属性和方法,使用对象伪装继承实例属性。通 过定义原型方法,允许函数复用,并允许每个实例拥有它们自己的属性。参考以下代码:

 1 function BaseClass(name)
2 {
3 this.name = name;
4 this.colors = ["red","blue"];
5 }
6 BaseClass.prototype.getName = function(){return this.name;}
7
8 function ChildClass(name,age)
9 {
10 // inherit
11 BaseClass.call(this,name);
12 this.age = age;
13 }
14 // inherit
15 ChildClass.prototype = new BaseClass();
16
17 ChildClass.prototype.getAge = function(){return this.age;}
18
19 var instance1 = new ChildClass("sds1",28);
20 var instance2 = new ChildClass("sds2",29);
21 instance2.colors.push("green");
22 var instance3 = new ChildClass("sds3",30);
23
24 alert(instance1.colors);//red,blue
25 alert(instance1.getName());//sds1
26 alert(instance1.getAge());//28
27
28 alert(instance2.colors);//red,blue,green
29 alert(instance2.getName());//sds2
30 alert(instance2.getAge());//29
31
32 alert(instance3.colors);//red,blue
33 alert(instance3.getName());//sds3
34 alert(instance3.getAge());//30

    原型链和对象伪装的继承,它们各自有优缺点,并且是互补的,而组合继承正是利用了它们的这种互补性将其结合在一起,比较完美的实现了继承。通过上面的示 例,清楚的看到同时通过组合的方式ChildClass继承了BaseClass类,ChildClass类的三个实例的属性各不影响,且方法都是可复用 的原型方法。
    组合继承是使用最频繁的js继承方式,它的本质还是原型链和对象伪装。

posted @ 2011-09-17 13:27  腐乳  阅读(326)  评论(0编辑  收藏  举报