[Object]继承(经典版)(四)多重继承和组合继承

作者:zccst


一、多重继承
不得不说,这又是异常精彩的章节,是原型链的升华。

Js代码  收藏代码
  1. //父类1  
  2. function Parent1(name,age){  
  3.     this.name = name;  
  4.     this.age = age;  
  5.     this.height=180;  
  6. }  
  7. Parent1.prototype.say = function(){  
  8.     alert('hi...');  
  9. }  
  10.   
  11. //父类2  
  12. function Parent2(name,age,weight){  
  13.     this.name = name;  
  14.     this.age = age;  
  15.     this.weight = weight;  
  16.     this.height = 170;  
  17.     this.skin='yellow';  
  18. }  
  19. Parent2.prototype.walk = function(){  
  20.     alert('walk...');  
  21. }  
  22.   
  23. //子类  
  24. function Child(name,age,weight){  
  25.     Parent1.call(this,name,age);  
  26.     Parent2.call(this,name,age,weight);  
  27. }  
  28.   
  29. //建立联系  
  30. for(var i in Parent1.prototype){Child.prototype[i] = Parent1.prototype[i]}  
  31. for(var i in Parent2.prototype){Child.prototype[i] = Parent2.prototype[i]}  
  32.   
  33. var c1 = new Child('xiaoming',10,8);  
  34. console.log(c1);  





其实,多重继承才是真实的物理世界,有一位博友用多重继承实现了照片墙,甚是精彩。
可以说是受教了,开眼界了。

多重继承还是很强大的。
博主的主要思想是循环复制多个父类原型对象的属性和方法到子类的原型对象,这样子类就可以继承多个父类了。

照片墙是个很有说服力的例子。其关系是:

Photo //会选择,鼠标移上,鼠标离开
Child1 //继承Photo,重写鼠标移上,离开。目的是移上放大三倍,离开回到原来尺寸。
Child2 //继承Photo,实现旋转10-40度
Child3 //继承Child1和Child2,实现即放大三倍,有选择10-40度


二、组合继承

类似这样
function C(){
  B.call(this, xx);
  A.call(this, xx);
}

posted on 2015-02-13 11:06  山冈龙  阅读(188)  评论(0编辑  收藏  举报

导航