小方的Java博客

            BlogJava :: 首頁 :: 新隨筆 :: 聯(lián)系 :: 聚合  :: 管理 ::
            27 隨筆 :: 17 文章 :: 115 評論 :: 0 Trackbacks
          選自《Professional Javascript For Web Developers》

          其它方式:工廠方式,構造函數(shù)方式,原型方式都各有各的大缺陷,這里就不一一介紹了,想了解的可以去看一下這本著作的第3章節(jié)。

          1. 混合構造函數(shù)/原型方式

          function ?Car(sColor,?iDoors,?iMpg)?{
          ??
          this .color? = ?sColor;
          ??
          this .doors? = ?iDoors;
          ??
          this .mpg? = ?iMpg;
          ??
          this .drivers? = ? new ?Array(“Mike”,?“Sue”);
          }

          Car.prototype.showColor?
          = ? function ?()?{
          ??alert(
          this .color);
          };

          var ?oCar1? = ? new ?Car(“red”,? 4 ,? 23 );
          var ?oCar2? = ? new ?Car(“blue”,? 3 ,? 25 );

          oCar1.drivers.push(“Matt”);

          alert(oCar1.drivers);?
          // outputs?“Mike,Sue,Matt”
          alert(oCar2.drivers);? // outputs?“Mike,Sue”

          優(yōu)點:具有其它方式的優(yōu)點而沒有其它方式的缺點
          不足:封裝性欠缺

          2 . 動態(tài)原型方式

          function ?Car(sColor,?iDoors,?iMpg)? {
          ??
          this .color? = ?sColor;
          ??
          this .doors? = ?iDoors;
          ??
          this .mpg? = ?iMpg;
          ??
          this .drivers? = ? new ?Array(“Mike”,?“Sue”);

          ??
          if ?( typeof ?Car._initialized? == ?“undefined”)? {
          ????Car.prototype.showColor?
          = ? function ?()? {
          ??????alert(
          this .color);
          ????}
          ;

          ????Car._initialized?
          = ? true ;
          ??}

          }


          優(yōu)點:封裝性比上一個方式更好
          不足:就是看上去奇怪一點,呵呵


          總之,以上2種方式是目前最廣泛使用的,盡量使用它們避免不必要的問題。

          posted on 2007-02-11 17:34 方佳瑋 閱讀(6175) 評論(1)  編輯  收藏 所屬分類: AJAX

          評論

          # re: [整理]JavaScript最流行的2種定義類的方式 2007-02-11 20:46 BeanSoft
          // Method 1: flat array style quick object define
          var myObject = {
          username : "beansoft",
          age : 24,
          test : function() {alert(this.age);}
          };

          // Method 2: using Object
          var myObject = new Object();
          myObject.username = "beansoft";
          myObject.age = 24;

          // Method 3: using constructor

          function MyObject(username, age) {
          this.username = username;
          this.age = age;
          this.test = function() {alert(this.age);};
          }

          var myObject = new MyObject("beansoft", 24);

          // Method 4,5 如樓上文章所言既是

          // Using: myObject.username, myObject["username"], myObject[0]
          myObject.test();// Will display alert window, value is age
          myObject.username = "Hello";// Will asign the username property to "Hello"  回復  更多評論
            

          主站蜘蛛池模板: 平原县| 叶城县| 乌兰县| 灵寿县| 南和县| 永川市| 定西市| 黑河市| 江安县| 屯留县| 大余县| 宁陵县| 乐至县| 石渠县| 保康县| 涞源县| 长春市| 天长市| 惠安县| 阳谷县| 泊头市| 永德县| 武汉市| 万年县| 英超| 田林县| 永新县| 乡宁县| 钦州市| 苍山县| 大安市| 邵东县| 台南县| 岳西县| 城固县| 玉树县| 遂昌县| 南陵县| 西峡县| 广东省| 开江县|