javascript继承(六)—实现多继承

在上一篇javascript继承—prototype最优两种继承(空函数和循环拷贝)(3) ,介绍了js较完美继承的两种实现方案,那么下面来探讨一下js里是否有多继承,如何实现多继承。在这里可以看看java是如何处理多继承的问题,java里是没有多继承的,即一个子类不能同时继承多个父类,但可以实现多个接口,这也间接的实现了多继承。主要是因为多继承涉及到成员变量重名的问题,对于java这种强类型语言,是很不好操作的。所以java让接口成的成员变量只能定义为常量。这也解决了实现多个接口的问题。

对于js来说,如何实现一个子类继承多个父类呢?怎样让父类的特权属性和共有方法实现比较完美的继承呢?参考上一篇中的两种继承方式。会发现多继承是不能用空函数来实现的,下面具体说明如何操作。

function Parent1(name,age){
    this.name = name;
    this.age = age;
    this.height=180;
}
Parent1.prototype.say = function(){
    alert('hi...');
}
function Parent2(name,age,weight){
    this.name = name;
    this.age = age;
    this.weight = weight;
    this.height = 170;
    this.skin='yellow';
}
Parent2.prototype.walk = function(){
    alert('walk...');
}

function Child(name,age,weight){
    Parent1.call(this,name,age);
    Parent2.call(this,name,age,weight);
}

for(var i in Parent1.prototype){Child.prototype[i] = Parent1.prototype[i]}
for(var i in Parent2.prototype){Child.prototype[i] = Parent2.prototype[i]}

var c1 = new Child('xiaoming',10,8);
console.log(c1); //Child { name="xiaoming", age=10, height=170, 更多...}

age_thumb[1]

console.log(c1.constructor);//Child(name,age,weight)

可以看到子类Child的实例c1打出的结果继承了父类的所有属性和方法。当然这里存在一个问题,如果父类Parent1和Parent2都有name这个属性的时候,会以后继承的为主。即这里c1的name属性为170,覆盖了Parent1的属性180。

可以理解javascript的多继承其实就是前面介绍的js循环拷贝继承的多次使用。下面来讲讲为什么空函数继承的方法是不行的。同样举例说明:

二、用空函数实现多继承(此方法不行)

function Parent1(name,age){
    this.name = name;
    this.age = age;
    this.height=180;
}
Parent1.prototype.say = function(){
    alert('hi...');
}
function Parent2(name,age,weight){
    this.name = name;
    this.age = age;
    this.weight = weight;
    this.height = 170;
    this.skin='yellow';
}
Parent2.prototype.walk = function(){
    alert('walk...');
}

function Child(name,age,weight){
    Parent1.call(this,name,age);
    Parent2.call(this,name,age,weight);
}
function Empty1(){}
Empty1.prototype = Parent1.prototype;//将Parent1的prototype赋给Empty1的prototype
Child.prototype = new Empty1(); //将Empty1的实例赋给Child的prototype

//同样对于Parent2也使用这种方法时
function Empty2(){}
Empty2.prototype = Parent2.prototype;
Child.prototype = new Empty2(); //这里Child的prototype已经有了Parent1的共有方法,这里将Parent2的方法赋过来,是覆盖
Child.prototype.constructor = Child;

var c1 = new Child('xiaoming',10,8);
console.log(c1.constructor);//Child(name,age,weight)
console.log(c1); //Child { name="xiaoming", age=10, height=170, 更多...}
 
age_thumb[4]
 

可以看到子类的实例只有walk方法,而Parent1的say方法被覆盖了。

总结:javascript是可以利用call方法和prototype属性来实现多继承的。继承方法与单继承相似,只是将需要继承的多个父类依次实现,另外对于属性或共有方法重命的时候,以最后继承的属性和方法为主。因为会覆盖前面的继承。

posted @ 2014-06-12 16:37  jssl915  阅读(12959)  评论(0编辑  收藏  举报