• 关于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继承方式,它的本质还是原型链和对象伪装。

  • 相关阅读:
    libeXosip2(1-2) -- How-To initiate, modify or terminate calls.
    libeXosip2(1-1) -- How-To initialize libeXosip2.
    libeXosip2(1) -- Modules
    麦田的守望者背景与分析
    statfs函数说明
    c++ 14
    c++ 13
    URAL 2078~2089
    2018 Multi-University Training Contest 1
    Codeforces Round #502
  • 原文地址:https://www.cnblogs.com/405464904/p/2179583.html
Copyright © 2020-2023  润新知