您的位置:首页 > Web前端 > JavaScript

javascript的继承种类

2015-09-11 16:54 537 查看
继承一般要实现以下三层含义:

1)子类实例可以共享父类的方法;

2)子类可以覆盖父类的方法或者扩展新的方法;

3)子类和父类都是子类实例的类型。

一、构造继承法

子类中调用父类的构造函数来维护的,该继承法能实现多重继承,但只能继承父类的共有方法,无法继承静态方法,而且不能用instanceof来验证实例。

function a(){
this.say=function(){
alert("happy new year!");
}
}

function b(){
a.apply(this,arguments);
}

a.prototype.fuck=function(){
alert("%^&%^&%&^%&");
}

var oB=new b();
alert(oB instanceof a);// false
oB.say(); // happy new year
oB.fuck(); // 读不到

二、原型继承法/经典继承法

该继承法是通过复制已经存在的原型对象来实现行为重用,让对象实例共享原型对象的属性。支持多重继承,继承原型静态方法,能用instanceof来验证实例。

function a(){
this.say=function(){
alert("happy new year!");
}
}

function b(){}

a.prototype.fuck=function(){
alert("%^&%^&%&^%&");
}

a.prototype.z=123;
b.prototype=new a();

var oB=new b();
alert(oB instanceof a); // true
alert(oB.z); // 123
oB.say(); // happy new year
oB.fuck(); // %^&%^&%&^%&

三、实例继承法/寄生构造函数模式

构造法不能继承类型的静态方法,原型继承得不完善(某些核心对象的不可枚举方法不能继承),而实例继承法能对原生核心对象或者DOM对象进行继承,它通过在类型中构造对象并返回的办法来实现继承,因此instanceof验证会是false,不支持多重继承。

function a(){
var oA=new Array();
oA.say=function(){
alert("hello A!");
}
return oA;
}

var obj=new a();
alert(obj instanceof a); // false
obj.say();

四、拷贝继承法

该方法通过拷贝基类对象的所有可枚举属性和方法来模拟继承,因此它可以模拟多继承,但不能枚举的就无法继承;它可以继承父类的静态方法;

function a(){
this.num=123;
this.say=function(){
alert("happy new year!");
}
}

function b(){
this.extends=function(obj){
for(each in obj){
this[each]=obj[each];
}
}
}

var oB=new b();
oB.extends(new a());

alert(oB instanceof a); // false
alert(oB.num); // 123
oB.say(); // happy new year

五、混合继承法

顾名思义就是把上面几种继承法综合起来,取长补短,让继承更完善。常见的有 构造+原型继承:伪经典继承

function a(){
this.num=123;
this.say=function(){
alert("happy new year!");
}
}

function b(){
a.apply(this);
}

b.prototype=new a();
b.prototype.z=123;

var oB=new b();
alert(oB instanceof a); // true
alert(oB.num); // 123
oB.say(); // happy new year

六、各种继承法的优缺点



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: