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);
          }
          主站蜘蛛池模板: 榕江县| 喜德县| 益阳市| 昭苏县| 兴海县| 阳高县| 宁乡县| 海兴县| 四川省| 壶关县| 阳新县| 西宁市| 江阴市| 弋阳县| 依兰县| 吉林市| 海城市| 会昌县| 长汀县| 德清县| 高平市| 错那县| 临湘市| 鲁山县| 冀州市| 澄江县| 安图县| 台南县| 建德市| 牟定县| 德兴市| 曲靖市| 承德市| 栖霞市| 清新县| 札达县| 子长县| 绥化市| 闽清县| 三门峡市| 金昌市|