javascript 類定義的4種方法
更新時(shí)間:2009年09月12日 21:51:47 作者:
javascript 類定義的4種方法,大家可以參考下根據(jù)需要選擇。
復(fù)制代碼 代碼如下:
/*
工廠方式--- 創(chuàng)建并返回特定類型的對(duì)象的 工廠函數(shù) ( factory function )
*/
function createCar(color,doors,mpg){
var tempCar = new Object;
tempCar.color = color;
tempCar.doors = doors;
tempCar.mpg = mpg;
tempCar.showCar = function(){
alert(this.color + " " + this.doors);
}
return tempCar;
}
/*
構(gòu)造函數(shù)方式--- 構(gòu)造函數(shù)看起來很像工廠函數(shù)
*/
function Car(color,doors,mpg){
this.color = color;
this.doors = doors;
this.mpg = mpg;
this.showCar = function(){
alert(this.color);
};
}
/*
原型方式--- 利用了對(duì)象的 prototype 屬性,可把它看成創(chuàng)建新對(duì)象所依賴的原型
*/
function Car(color,doors,mpg){
this.color = color;
this.doors = doors;
this.mpg = mpg;
this.drivers = new Array("nomad","angel");
}
Car.prototype.showCar3 = function(){
alert(this.color);
};
/*
混合的構(gòu)造函數(shù) /原型方式--- 用構(gòu)造函數(shù)定義對(duì)象的所有非函數(shù)屬性,用原型方式定義對(duì)象的函數(shù)屬性(方法)
*/
function Car(sColor, iDoors, iMpg) {
this.color = sColor;
this.doors = iDoors;
this.mpg = iMpg;
this.drivers = new Array("Mike", "Sue");
}
Car.prototype.showColor = function () {
alert(this.color);
};
/*
動(dòng)態(tài)原型方法--- 在構(gòu)造函數(shù)內(nèi)定義非函數(shù)屬性,而函數(shù)屬性則利用原型屬性定義。唯一的區(qū)別是賦予對(duì)象方法的位置。
*/
function Car(sColor, iDoors, iMpg) {
this.color = sColor;
this.doors = iDoors;
this.mpg = iMpg;
this.drivers = new Array("Mike", "Sue");
if (typeof Car._initialized == "undefined") {
Car.prototype.showColor = function () {
alert(this.color);
};
Car._initialized = true;
}
} //該方法使用標(biāo)志( _initialized )來判斷是否已給原型賦予了任何方法。
相關(guān)文章
用JavaScript實(shí)現(xiàn)單繼承和多繼承的簡單方法
JavaScript是一種強(qiáng)大的多泛型編程語言,其融合了面向過程、面向?qū)ο蠛秃瘮?shù)式編程于一身,具備強(qiáng)大的表現(xiàn)能力。2009-03-03
不錯(cuò)的JavaScript面向?qū)ο蟮暮唵稳腴T介紹
JavaScript是一門OOP,而有些人說,JavaScript是基于對(duì)象的。2008-07-07
Javascript面向?qū)ο缶幊蹋ǘ?構(gòu)造函數(shù)的繼承
這個(gè)系列的第一部分,主要介紹了如何"封裝"數(shù)據(jù)和方法,以及如何從原型對(duì)象生成實(shí)例。2011-08-08
編寫可維護(hù)面向?qū)ο蟮腏avaScript代碼[翻譯]
編寫可維護(hù)面向?qū)ο蟮腏avaScript代碼[翻譯],學(xué)習(xí)js面向?qū)ο缶帉懙呐笥芽梢詤⒖枷隆?/div> 2011-02-02
JavaScript面向?qū)ο笤O(shè)計(jì)二 構(gòu)造函數(shù)模式
在Javascript面向?qū)ο笤O(shè)計(jì)一——工廠模式 中介紹了使用CreateEmployee()函數(shù)創(chuàng)建員工類。ECMAScript中的構(gòu)造函數(shù)可以用來創(chuàng)建特定類型的對(duì)象,如Object和Array這樣的原生構(gòu)造函數(shù),在運(yùn)行時(shí)會(huì)自動(dòng)出現(xiàn)在執(zhí)行環(huán)境中,此外也可以創(chuàng)建自定義的構(gòu)造函數(shù),從而創(chuàng)建自定義對(duì)象類型的屬性和方法2011-12-12
Javascript面向?qū)ο髷U(kuò)展庫代碼分享
最近一直在用js做項(xiàng)目,遇到了許多需要應(yīng)用面向?qū)ο髞碓O(shè)計(jì)的功能,由于js對(duì)OOP的原生支持還不是很完善,所以就寫了一個(gè)面向?qū)ο蟮臄U(kuò)展庫用做底層支持,現(xiàn)在把它單獨(dú)整理出來,完善了一些功能,在這里分享一下2012-03-03最新評(píng)論

