脚本宝典收集整理的这篇文章主要介绍了javascript代码实例教程-javascript―实现多继承,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。小宝典致力于为广大程序猿(媛)提供高品质的代码服务,请大家多多光顾小站,小宝典在此谢过。 探讨一下js里是否有多继承,如何实现多继承。在这里可以看看java是如何处理多继承的问题,java里是没有多继承的,即一个子类不能同时继承多个父类,但可以实现多个接口,这也间接的实现了多继承。主要是因为多继承涉及到成员变量重名的问题,对于java这种强类型语言,是很不好操作的。所以java让接口成的成员变量只能定义为常量。这也解决了实现多个接口的问题。
对于js来说,如何实现一个子类继承多个父类呢?怎样让父类的特权属性和共有方法实现比较完美的继承呢?参考上一篇中的两种继承方式。会发现多继承是不能用空函数来实现的,下面具体说明如何操作。
复制代码
function Parent1(name,age){
this.name = name;
this.age = age;
this.height=180;
}
Parent1.PRototyPE.say = function(){
}
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属性来实现多继承的。继承方法与单继承相似,只是将需要继承的多个父类依次实现,另外对于属性或共有方法重命的时候,以最后继承的属性和方法为主。因为会覆盖前面的继承
觉得可用,就经常来吧! 脚本宝典 欢迎评论哦! js脚本,巧夺天工,精雕玉琢。小宝典献丑了!
以上是脚本宝典为你收集整理的javascript代码实例教程-javascript―实现多继承全部内容,希望文章能够帮你解决javascript代码实例教程-javascript―实现多继承所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。