在上一篇javascript继承—prototype最优两种继承(空函数和循环拷贝)(3) ,介绍了js较完美继承的两种实现方案,那么下面来探讨一下js里是否有多继承,如何实现多继承。在这里能够看看java是如何处理多继承的问题,java里是没有多继承的,即一个子类不能同时继承多个父类,但能够实现多个接口,这也间接的实现了多继承。主要是由于多继承涉及到成员变量重名的问题,对于java这种强类型语言,是很很差操做的。因此java让接口成的成员变量只能定义为常量。这也解决了实现多个接口的问题。javascript
对于js来讲,如何实现一个子类继承多个父类呢?怎样让父类的特权属性和共有方法实现比较完美的继承呢?参考上一篇中的两种继承方式。会发现多继承是不能用空函数来实现的,下面具体说明如何操做。html
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, 更多...}
console.log(c1.constructor);//Child(name,age,weight)
能够看到子类Child的实例c1打出的结果继承了父类的全部属性和方法。固然这里存在一个问题,若是父类Parent1和Parent2都有name这个属性的时候,会之后继承的为主。即这里c1的name属性为170,覆盖了Parent1的属性180。java
能够理解javascript的多继承其实就是前面介绍的js循环拷贝继承的屡次使用。下面来说讲为何空函数继承的方法是不行的。一样举例说明:函数
2、用空函数实现多继承(此方法不行)this
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, 更多...}
能够看到子类的实例只有walk方法,而Parent1的say方法被覆盖了。spa
总结:javascript是能够利用call方法和prototype属性来实现多继承的。继承方法与单继承类似,只是将须要继承的多个父类依次实现,另外对于属性或共有方法重命的时候,以最后继承的属性和方法为主。由于会覆盖前面的继承。prototype