Flyingis

          Talking and thinking freely !
          Flying in the world of GIS !
          隨筆 - 156, 文章 - 16, 評(píng)論 - 589, 引用 - 0
          數(shù)據(jù)加載中……

          JavaScript 中的繼承(下)

          ??? 作者:Flyingis

          ??? Prototype

          ??? 在《JavaScript中的對(duì)象(下)》一文中,我們了解到任何prototype的屬性和方法都會(huì)被傳遞到該類的所有實(shí)例中,利用這一特性,使用prototype也能實(shí)現(xiàn)繼承。
          ?
          function ClassA()? {
          }


          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);
          }

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

          ??? 對(duì)代碼進(jìn)行測(cè)試:

          var ?obj1 = new ClassA();
          var ?obj2 = new ClassB();
          obj1.id
          =?1998;
          obj2.id
          =?2000;
          obj2.name
          ="悉尼奧運(yùn)會(huì)";
          obj1.sayId();??
          //輸出"1998"
          obj2.sayId();??//輸出"1998"
          obj2.sayName();??//輸出"悉尼奧運(yùn)會(huì)"

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

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

          ??? 混合方法

          ??? 《JavaScript中的對(duì)象(下)》一文中曾經(jīng)論述,創(chuàng)建一個(gè)類的最佳方法,是使用構(gòu)造器的方法去定義屬性,使用prototype定義方法。在繼承中同樣如此。

          function ClassA(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);
          }

          posted on 2006-07-15 16:53 Flyingis 閱讀(1564) 評(píng)論(0)  編輯  收藏 所屬分類: Web 客戶端技術(shù)

          主站蜘蛛池模板: 会理县| 普定县| 南京市| 静宁县| 陇南市| 大余县| 环江| 霍山县| 三穗县| 桃园县| 扎兰屯市| 弥渡县| 阿合奇县| 青龙| 永济市| 昂仁县| 宁河县| 平顺县| 嵊泗县| 通化县| 合水县| 遂平县| 扎兰屯市| 玉龙| 合江县| 长岛县| 长沙市| 县级市| 东乌珠穆沁旗| 思南县| 托克托县| 宁南县| 丰台区| 鹰潭市| 安乡县| 揭东县| 博罗县| 栾川县| 通山县| 丁青县| 榆中县|