轉自:http://www.cnblogs.com/snandy/archive/2011/03/06/1972254.html
這篇開始會記錄一些寫類的工具函數,通過上篇我們知道本質上都是 建構函式+原型。理解了它碰到各式各樣的寫類方式就不懼怕了。
建構函式 + 原型 直接組裝一個類;同一建構函式將組裝出同一類型
03 |
* @param {Function} constructor |
04 |
* @param {Object} prototype |
06 |
function $class(constructor,prototype) { |
07 |
var c = constructor || function(){}; |
08 |
var p = prototype || {}; |
用建構函式來產生類執行個體的屬性(欄位),原型對象用來產生類執行個體的方法。
02 |
function Person(name) { |
07 |
getName : function(){return this.name}, |
08 |
setName : function(name){this.name = name;} |
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"); |
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 || {}; |
6 |
c.prototype[atr] = p[atr]; |