继承一般包括 单向继承 和 多重继承
多重继承:一个子类继承多个超类
function A(x){this.x=x;}
A.prototype.getx=function(){return this.x;}
function B(y){this.y=y;}
B.prototype.gety=function(){return this.y;}
function C(x,y){}
Function.prototype.extend=function(o){//方法一,使用复制继承
for(var i in o){this.constructor.prototype[i]=o[i];}
}
function C(x,y){//方法二,使用类继承
A.call(this.x)
B.call(this.y)
}
C.extend(new A(10));
C.extend(new B(20));
alert(C.x)//10 alert(C.y)//20 alert(C.getx());//10 alert(C.gety());20
掺元类:一个类被多个类继承,成为多亲继承,这个被多个类继承的类称为掺元类
var F=function(x,y){this.x=x;this.y=y}
F.prototype={
getx:function(){return this.x;},
gety:function(){return this.y;}
}
A=function(x,y){F.call(this,x,y)};//类继承
B=function(x,y){F.call(this,x,y)}
//使用原型继承方法,但是原型继承需要实例化类F,可以专门模仿复制继承设计一个专门函数来实现这种继承关系
function extend(Sub,Sup){//掺元类继承封装函数
for(m in Sup.prototype){//遍历掺元类的原型对象
if(!Sub.prototype[m]){Sub.prototype[m]=Sup.prototype[m];}//如果子类没有存在同名成员,进行复制
}
}
extend(A,F);
extend(B,F);
var a=new A(1,2) // 实例化后就可以调用F的通用方法
var b=new B(10,20)
也可以利用这两种方法,把多个子类合并到一个类中,实现多重继承
var A=function(){}
A.prototype={
x:function(){return 'x'}
}
var B=function(){}
B.prototype={
y:function(){return 'y'}
}
C=function(){};
extend(C,A);
extend(C,B);
var c=new C();
alert(c.x());alert(c.y())