js的对象继承

js对象继承方式不止一种,而且是模仿实现的继承。

 1、对象冒充方式:

    例子:

      function ClassA(color){

        this.color = color;

        this.showColor = function(){

          alert(this.color);

        }

      }

      function ClassB(color,name){

        this.method = ClassA;    //将ClassB的对象的method属性指向ClassA函数,这里把ClassA当作一个函数。

        this.method(color);   //将ClassB的对象传递给ClassA,this指向调用此函数的对象。

        this.name = name;

      }

      var b = new ClassB("red");

      b.showColor(); // 结果是"red";

      也可以使用call和apply方法实现冒充方式的继承,这是ECMAScript为了支持对象冒充而定义的方法。

      使用call方法:父类还是上面的ClassA,ClassB变为

      funciton ClassB(color,name){

        ClassA.call(this,color);

        this.name = name;

      }

      这样ClassB就继承自ClassA了。

     使用apply方法:父类还是上面的ClassA,ClassB变为

      function ClassB(color,name){

        ClassA.apply(this,color);

        this.name = name;

      }

     此种继承下 b instanceof ClassA为false。

      个人理解:call和apply方法有点儿类似于java中反射中的Method.invoke()方法。

  2、使用原型方式实现

     function ClassA(){}

     ClassA.prototype.color = "red";

     ClassA.prototype.showColor = function(){

      alert(this.color);

     }

     ClassB.prototype = new ClassA();//书上说是为了把ClassA的对象的所有属性和方法赋予ClassB的prototype属性。为何不用ClassA.prototype = ClassB.prototype呢,不明白,求指教。

     var b = new ClassB();

     b.color = 'blue';

     b.showColor();   //结果为blue;

     这种方式下b instanceof ClassA 的结果为true。

   3、使用混合方式

    function ClassA(color){

       this.color = color;

       this.name = name;

    }

    ClassA.prototype.showColor =  function(){

      alert(this.color);

    }

    function ClassB(color,name){

      this.temp = ClassA();    //使用对象冒充的方式继承ClassA的属性

      this.temp(color);

      this. name = name;

    }

    ClassB.prototype = new ClassA();  //使用原型方式继承ClassA的方法

    ClassB.prototype.showName() = function(){  //ClassB自己的方法

      alert(this.name);

    }

    var b = new ClassB('red','Tom');

    b.showColor();  //结果为'red';

    b.showName(); //结果为'Tom';

    这种方式下b instanceof ClassA的结果仍为true。

    

posted @ 2013-05-14 09:32  依伦  阅读(376)  评论(0)    收藏  举报