欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

javascript 寫類方式之四

 更新時(shí)間:2009年07月05日 01:36:00   作者:  
構(gòu)造函數(shù) + 原型 直接組裝一個(gè)類;同一構(gòu)造函數(shù)將組裝出同一類型
4、構(gòu)造函數(shù) + 原型 直接組裝一個(gè)類;同一構(gòu)造函數(shù)將組裝出同一類型
通過前面幾篇得知javascript寫類無非基于構(gòu)造函數(shù) 和原型 。既然這樣,我們寫個(gè)工具函數(shù)來寫類。
復(fù)制代碼 代碼如下:

/**
* $class 寫類工具函數(shù)之一
* @param {Object} 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í)例的方法。
復(fù)制代碼 代碼如下:

//構(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);

ok,這時(shí)候已經(jīng)得到了兩個(gè)類Man,Woman。并且是同一個(gè)類型的。測試如下:
復(fù)制代碼 代碼如下:

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

創(chuàng)建對象看看,
復(fù)制代碼 代碼如下:

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一切如我們所期望。但是有個(gè)問題,下面代碼的結(jié)果輸出false,
復(fù)制代碼 代碼如下:

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

這讓人不悅:從以上的代碼看出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)造器的原型),如下:
復(fù)制代碼 代碼如下:

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;
}

相關(guān)文章

最新評論