javascript面向对象编程--继承--类继承2(封装类继承模式)

function extend(Sub,Sup){

    var F=function(){};

  F.prototype=Sup.prototype;

  Sub.prototype=new F();

 Sub.prototype.constructor=Sub;

Sub.sup=Sup.prototype;// 在子类中定义一个本地属性存储超类原型,这样可以避免子类和超累耦合

if(Sup.prototype.constructor==Object.prototype.constructor){//检测超类的原型构造器是否为自身

    Sup.prototype.constructor=Sup //类继承 封装函数

}

}

function A(x){

  this.x=x;

this.get=function(){return this.x;}

}

A.prototype.add=funciton(){return this.x+this.x}

A.prototype.mul=funciton(){return this.x*this.x}

function B(x){

 A.call(this,x)   //

}

extend(B,A);

B.prototype.add=function(){  return this.x+''+this.x}//55,覆盖了超类A的原型方法

B.prototype.add=function(){  return B.sup.add.call(this)}//在B类调用超类A的原型方法,避免代码耦合现象发生

 

var f=new B(5);

alert(f.get()) //5

alert(f.add())//10

alert(f.mul())//25

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值