javascript 继承

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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值