淺析JavaScript的寫類方式(2)
這篇開始會記錄一些寫類的工具函數(shù),通過上篇我們知道本質(zhì)上都是 構(gòu)造函數(shù)+原型。理解了它碰到各式各樣的寫類方式就不懼怕了。以下列舉的有的是工作中碰到的,有的是從書籍或網(wǎng)上收集的。見過的朋友就忽視它吧。
51CTO推薦專題:JavaScript函數(shù)式編程
構(gòu)造函數(shù) + 原型 直接組裝一個類;同一構(gòu)造函數(shù)將組裝出同一類型
- /**
- * $class 寫類工具函數(shù)之一
- * @param {Function} constructor
- * @param {Object} prototype
- */
- function $class(constructor,prototype) {
- var c = constructor || function(){};
- var p = prototype || {};
- c.prototype = p;
- return c;
- }
用構(gòu)造函數(shù)來生成類實(shí)例的屬性(字段),原型對象用來生成類實(shí)例的方法。
- //構(gòu)造函數(shù)
- function Person(name) {
- this.name = name;
- }
- //原型對象
- var proto = {
- getName : function(){return this.name},
- setName : function(name){this.name = name;}
- }
- //組裝
- var Man = $class(Person,proto);
- var Woman = $class(Person,proto);
這時候已經(jīng)得到了兩個類Man,Woman。并且是同一個類型的。測試如下:
- console.log(Man == Woman); //true
- console.log(Man.prototype == Woman.prototype); //true
創(chuàng)建對象看看
- var man = new Man("Andy");
- var woman = new Woman("Lily");
- console.log(man instanceof Man); //true
- console.log(woman instanceof Woman); //true
- console.log(man instanceof Person); //true
- console.log(woman instanceof Person); //true
ok,一切如我們所期望。但是有個問題,下面代碼的結(jié)果輸出false
- console.log(man.constructor == Person);//false<br>
這讓人不悅:從以上的代碼看出man的確是通過Man類new出來的 var man = new Man("Andy"),那么對象實(shí)例man的構(gòu)造器應(yīng)該指向Man,但為何事與愿違呢?
原因就在于$class中重寫了Person的原型:c.prototype = p;
好了,我們把$class稍微改寫下,將方法都掛在構(gòu)造器的原型上(而不是重寫構(gòu)造器的原型),如下:
- function $class(constructor,prototype) {
- var c = constructor || function(){};
- var p = prototype || {};
- // c.prototype = p;
- for(var atr in p){
- c.prototype[atr] = p[atr];
- }
- return c;
- }
原文鏈接:http://www.cnblogs.com/snandy/archive/2011/03/06/1972254.html
【編輯推薦】