javascript 继承

来源:互联网 发布:c语言代码基础 编辑:程序博客网 时间:2024/06/07 17:43

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();

0 0
原创粉丝点击