天天看点

javascript 继承实现方式

call()方法

call()方法是与经典的对象冒充方法最相似的方法。它将第一个参数作this的对象。其它参数都是直接传给函数自身。例如:

   function ClassA(sColor){

    this.color=sColor;

    this.sayColor=function(){

     alert(this.color);

    }

   }

   function ClassB(sColor,sName){

    ClassA.call(this,sColor);

    this.name=sName;

    this.sayName=function(){

     alert(this.sayName);

    }

   }

   var oB=new ClassB('red','redName');

   oB.sayColor();  //继承了ClassA的方法。

   这里,想让ClassA的关键字this等于新创建的ClassB对象,因此this是第一个参数。第二个参数sColor对两个类都是唯一的参数。 

继续阅读