這篇開始會記錄一些寫類的工具函數,通過上篇我們知道本質上都是 建構函式+原型。理解了它碰到各式各樣的寫類方式就不懼怕了。
建構函式 + 原型 直接組裝一個類;同一建構函式將組裝出同一類型
view sourceprint?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 }
用建構函式來產生類執行個體的屬性(欄位),原型對象用來產生類執行個體的方法。
view sourceprint?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。並且是同一個類型的。測試如下:
view sourceprint?1 console.log(Man == Woman); //true
2 console.log(Man.prototype == Woman.prototype); //true
建立對象看看
view sourceprint?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
view sourceprint?1 console.log(man.constructor == Person);//false<BR>
這讓人不悅:從以上的代碼看出man的確是通過Man類new出來的 var man = new Man("Andy"),那麼對象執行個體man的構造器應該指向Man,但為何事與願違呢?
原因就在於$class中重寫了Person的原型:c.prototype = p;
好了,我們把$class稍微改寫下,將方法都掛在構造器的原型上(而不是重寫構造器的原型),如下:
view sourceprint?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 }