JavaScript的寫類方式(2)——轉

來源:互聯網
上載者:User

轉自:http://www.cnblogs.com/snandy/archive/2011/03/06/1972254.html

 

這篇開始會記錄一些寫類的工具函數,通過上篇我們知道本質上都是 建構函式+原型。理解了它碰到各式各樣的寫類方式就不懼怕了。

 

建構函式 + 原型 直接組裝一個類;同一建構函式將組裝出同一類型

01 /**
02  * $class 寫類工具函數之一
03  * @param {Function} constructor
04  * @param {Object} prototype
05  */
06 function $class(constructor,prototype) {
07     var c = constructor || function(){};
08     var p = prototype || {};
09     c.prototype = p;
10     return c;
11 }

用建構函式來產生類執行個體的屬性(欄位),原型對象用來產生類執行個體的方法。 

01 //建構函式
02 function Person(name) {
03     this.name = name;
04 }
05 //原型對象
06 var proto = {
07     getName : function(){return this.name},
08     setName : function(name){this.name = name;} 
09 }
10 //組裝
11 var Man = $class(Person,proto);
12 var Woman = $class(Person,proto);

這時候已經得到了兩個類Man,Woman。並且是同一個類型的。測試如下:

1 console.log(Man == Woman); //true
2 console.log(Man.prototype == Woman.prototype); //true

建立對象看看

1 var man = new Man("Andy");
2 var woman = new Woman("Lily");
3   
4 console.log(man instanceof Man); //true
5 console.log(woman instanceof Woman); //true
6 console.log(man instanceof Person); //true
7 console.log(woman instanceof Person); //true

ok,一切如我們所期望。但是有個問題,下面代碼的結果輸出false

1 console.log(man.constructor == Person); //false

這讓人不悅:從以上的代碼看出man的確是通過Man類new出來的 var man = new Man("Andy"),那麼對象執行個體man的構造器應該指向Man,但為何事與願違呢?

原因就在於$class中重寫了Person的原型:c.prototype = p; 
好了,我們把$class稍微改寫下,將方法都掛在構造器的原型上(而不是重寫構造器的原型),如下:

1 function $class(constructor,prototype) {
2     var c = constructor || function(){};
3     var p = prototype || {};
4 //  c.prototype = p;
5     for(var atr in p){
6         c.prototype[atr] = p[atr];
7     }   
8     return c;
9 }

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.