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

猜你喜欢

转载自blog.csdn.net/wenmin1987/article/details/82823217