1.默认继承
function child(){}
function Parent(){}
child.prototype=new Parent(); //注意:原型属性指向的是对象而不是一个函数
缺点:每次需要一个新的子对象是就要重新创建父对象,也就是反复的重新创建父对象,效率低下
2.apply(),call()
function Parent(){}
function child(){
Paren.call(this);
}
缺点:无法继承原型中任何一个属性,但是可以获取父对象自身成员的真是副本;
例子:
function Parent1(){
this.name="Parent1";
this.wang="nu";
}
function Parent2(){
this.name="Parent2";
}
function child(){
Parent1.call(this);
Parent2.call(this);
}
$(function(){
var c1=new child();
alert(c1.name) ; //Parent2
c1.name="dd";
alert(c1.name); //dd
var c2=new Parent1();
alert(c2.name); //Parent1
})
3.共享原型
function Parent(){}
function child(){}child.prototype=Parent.prototype;
缺点:子对象改变会影响所有的父对象和祖先对象
例子:
function Parent(){
this.name="Parent1";
this.wang="nu";
}
Parent.prototype.high=12;
function Child(){
}
Child.prototype=Parent.prototype;
Child.prototype.high=34;
$(function(){
var c1=new Child();
alert(c1.high); //34
var p1=new Parent();
alert(p1.high);//34
})
4.对3的优化
加一个临时构造函数
function Parent(){
this.name="Parent1";
this.wang="nu";
}
Parent.prototype.high=12;
function Child(){
}
function Tem(){}
Tem.prototype=Parent.prototype;
Child.prototype=new Tem();
本文详细介绍了JavaScript中的四种经典继承方式:默认继承、使用apply/call方法、共享原型以及通过临时构造函数优化共享原型的方式。每种方式都有其优缺点,并通过具体示例展示了不同继承方式的效果。
1001

被折叠的 条评论
为什么被折叠?



