javascript面向对象编程--继承--类继承1(构造函数继承)

例1:函数之间的引用和传递是类继承的基础

function() A(x){

this.x=x;

this.say=function(){

alert(this.x)

}

}

function B(x,y){

  this.m=A; //把A当作一个普通函数引用给临时方法m()

this.m(x);  //

delete this.m; //清除临时方法,单继承

this.y=y;

this.call=function(){ //本地方法call()

alert(this.y)

}

}

var a=new A(1);

var b=new b(2,3);

a.say();//1

b.say();//2

b.call();//3

例2:例1的基础上设计一个类继承多个类

function A(x){

  this.x=funtion(){

     alert(x)   

   }

}

function B(y){

  this.y=funtion(){

     alert(y)   

   }

}

function C(x,y){

   this.m=A;

  this.m(x);

 this.m=B;

this.m(y)

}

var c=new C(2,3);

c.x();//2

c.y();//3

注:没有通过使用delete删除临时方法m(),而是同过覆盖的方法代替,不会影响继承的关系实现

例3:以上的设计模式太随意,严谨的设计模式应该考虑到各种可能存在的情况和类继承中的相互耦合

   function A(x){

    this.x=x;

}

A.prototype.getx=function(){return this.x}

function B(x,y){

    this.y=y;

   A.call(this.x);//

}

B.prototype=new A();//建立继承关系

B.prototype.constructor=B;//恢复B的原型对象的构造函数为B

B.prototype.gety=function(){return  this.y}

 var f2=new B(10,20)

alert(f2.getx());//10,调用超类的方法getx()

alert(f2.gety());//20,调用子类自己的方法gety()

例4:再看一个多重继承

B继承了A的本地方法也通过原型链继承了原型方法,C也继承了AB的本地方法和原型链方法

function A(x){//基类

   this.get1=function(){

     return x;

   }

}

A.prototype.has=function(){

    return !(this.get1()===0)

}

funciton B(){//超类

   var a=[];

   a=Array.apply(a,arguments);//

   A.call(this.a.length);//

  this.add=function(){

        return a.push.apply(a,arguments);

   }

  this.geta=function(){

       return a;

   }

}

B.prototype=new A();

B.prototype.constructor=B;

B.prototype.str=function(){

   return this.geta().toString();

  }

function C(){//子类

    B.apply(this.arguments);

    this.sort=function(){

       var a=this.geta();

      a.sort.apply(a,arguments);

   }

}

C.prototype=new B();

C.prototype.constructor=C;

var b=new B(1,2,3,4);

alert(b.get1());

alert(b.has());

var c=new C(30,10,20,40);

c.add(6,5);

alert(c.geta())

c.sort();

alert(c.geta());//

alert(c.get1());//

alert(c.has());//

alert(c.str());//

猜你喜欢

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