国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

javascript 寫類方式之四

2024-05-06 14:15:00
字體:
供稿:網(wǎng)友
4、構(gòu)造函數(shù) + 原型 直接組裝一個(gè)類;同一構(gòu)造函數(shù)將組裝出同一類型
通過前面幾篇得知javascript寫類無非基于構(gòu)造函數(shù) 和原型 。既然這樣,我們寫個(gè)工具函數(shù)來寫類。
代碼如下:
/**
* $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í)例的屬性(字段),原型對(duì)象用來生成類實(shí)例的方法。
代碼如下:
//構(gòu)造函數(shù)
function Person(name) {
this.name = name;
}
//原型對(duì)象
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è)類型的。測(cè)試如下:
代碼如下:
console.log(Man == Woman);//true
console.log(Man.prototype == Woman.prototype);//true

創(chuàng)建對(duì)象看看,
代碼如下:
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,
代碼如下:
console.log(man.constructor == Person);//false

這讓人不悅:從以上的代碼看出man的確是通過Man類new出來的 var man = new Man("Andy"),那么對(duì)象實(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;
}
發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表

圖片精選

主站蜘蛛池模板: 天柱县| 安平县| 哈巴河县| 安新县| 丹江口市| 靖远县| 仁布县| 望江县| 湖州市| 河源市| 宜良县| 三都| 正蓝旗| 晋江市| 内黄县| 颍上县| 成安县| 刚察县| 浦县| 临西县| 涪陵区| 营口市| 平昌县| 宕昌县| 福建省| 临泽县| 屏山县| 庆阳市| 儋州市| 肃宁县| 巴林左旗| 雷州市| 靖江市| 来安县| 瑞安市| 吉隆县| 澎湖县| 镇江市| 惠安县| 康平县| 双峰县|