JavaScript中的繼承(下)

          Posted on 2006-11-28 23:14 Jaunt 閱讀(199) 評論(0)  編輯  收藏 所屬分類: JavaScript
          ? 作者: Flyingis?
          ??原載:http://www.aygfsteel.com/flyingis/archive/2006/07/15/58339.html
          ??? Prototype

          ???
          我們了解到任何prototype的屬性和方法都會被傳遞到該類的所有實例中,利用這一特性,使用prototype也能實現(xiàn)繼承。
          ?
          ? functionClassA()?{
          }


          ClassA.prototype.id
          =?1998;
          ?ClassA.prototype.sayId
          =function(){
          ?? alert(
          this.id);
          }
          ;

          functionClassB(){
          }


          ClassB.prototype
          =newClassA();
          ClassB.prototype.name
          ="";
          ?ClassB.prototype.sayName
          =function(){
          ?? alert(
          this.name);
          }

          ??? 需要注意的是,這種實現(xiàn)繼承的方法不能將參數(shù)傳入到ClassA的構(gòu)造器中,是一個缺陷。ClassB的所有屬性和方法必需在將ClassB的 prototype對象指向ClassA的實例之后進行附值。這樣做是因為,prototype指向一個新的對象,在此之前prototype的屬性和方法都被覆蓋銷毀。

          ??? 對代碼進行測試:

          var?obj1 =newClassA();
          var?obj2=new ClassB();
          obj1.id
          =?1998;
          obj2.id
          =?2000;
          obj2.name
          ="悉尼奧運會";
          obj1.sayId();??
          //輸出"1998"
          obj2.sayId();??//輸出"1998"
          obj2.sayName();??//輸出"悉尼奧運會"

          alert(obj2
          instanceofClassA);??//輸出"true"
          alert(obj2 instanceofClassB);??//輸出"true"

          ??? 在上述代碼中可以看出,使用prototype實現(xiàn)繼承,instanceof操作符出現(xiàn)了另外的用途,在用構(gòu)造起定義類實現(xiàn)繼承時,instanceof不會出現(xiàn)這種效果。但是使用prototype不能支持多重繼承。
          ??
          ??? 使用構(gòu)造器定義類實現(xiàn)繼承和使用prototype實現(xiàn)繼承均存在各自的缺陷,要避免出現(xiàn)這些情況,只有將兩者混合使用。

          ??? 混合方法

          ??? 創(chuàng)建一個類的最佳方法,是使用構(gòu)造器的方法去定義屬性,使用prototype定義方法。在繼承中同樣如此。

          ? functionClassA(id)?{
          ??
          this.id =id;
          }


          ? ClassA.prototype.sayId
          =?function() {
          ?? alert(
          this.id);
          }
          ;

          function ClassB(id,?name) {
          ?? ClassA.call(
          this,?id);
          ??
          this.name =name;
          }


          ClassB.prototype
          =? new ClassA();
          ?ClassB.prototype.sayName
          =function(){
          ?? alert(
          this.name);
          }
          主站蜘蛛池模板: 澄迈县| 花垣县| 青州市| 赤峰市| 剑阁县| 道真| 宝丰县| 全南县| 克什克腾旗| 永嘉县| 吉林市| 德钦县| 河曲县| 兰考县| 长武县| 叶城县| 任丘市| 德惠市| 双鸭山市| 胶州市| 永善县| 探索| 阳泉市| 忻州市| 徐汇区| 肃宁县| 华宁县| 麻城市| 绥芬河市| 周至县| 花垣县| 长春市| 丘北县| 缙云县| 师宗县| 海城市| 白玉县| 三都| 盐山县| 逊克县| 济源市|