javascript 類(lèi)定義的4種方法
更新時(shí)間:2009年09月12日 21:51:47 作者:
javascript 類(lèi)定義的4種方法,大家可以參考下根據(jù)需要選擇。
復(fù)制代碼 代碼如下:
/*
工廠方式--- 創(chuàng)建并返回特定類(lèi)型的對(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ù)看起來(lái)很像工廠函數(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ì)象所依賴(lài)的原型
*/
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 )來(lái)判斷是否已給原型賦予了任何方法。
您可能感興趣的文章:
- 淺談幾種常用的JS類(lèi)定義方法
- js類(lèi)定義函數(shù)時(shí)用prototype與不用的區(qū)別示例介紹
- Javascript類(lèi)定義語(yǔ)法,私有成員、受保護(hù)成員、靜態(tài)成員等介紹
- 一個(gè)簡(jiǎn)單的javascript類(lèi)定義例子
- JS類(lèi)定義原型方法的兩種實(shí)現(xiàn)的區(qū)別評(píng)論很多
- JS中類(lèi)或?qū)ο蟮亩x說(shuō)明
- JavaScript定義類(lèi)或函數(shù)的幾種方式小結(jié)
- JS類(lèi)中定義原型方法的兩種實(shí)現(xiàn)的區(qū)別
- 關(guān)于js類(lèi)的定義
- JS類(lèi)的定義與使用方法深入探索
相關(guān)文章
js定義對(duì)象簡(jiǎn)單學(xué)習(xí)例子
js定義對(duì)象簡(jiǎn)單學(xué)習(xí)例子...2007-09-09

關(guān)于JavaScript定義類(lèi)和對(duì)象的幾種方式
在說(shuō)這個(gè)話題之前,我想先說(shuō)幾句題外話:最近偶然碰到有朋友問(wèn)我“hoisting”的問(wèn)題。即在js里所有變量的聲明都是置頂?shù)模x值則是在之后發(fā)生的。
2010-11-11 
JavaScript類(lèi)和繼承 this屬性使用說(shuō)明
本文介紹了JavaScript里面的this屬性。這個(gè)屬性是理解JavaScript類(lèi)和繼承的重要基礎(chǔ)。
2010-09-09 
javascript 面向?qū)ο笕吕砭氈^承與多態(tài)
前面我們討論了如何在 JavaScript 語(yǔ)言中實(shí)現(xiàn)對(duì)私有實(shí)例成員、公有實(shí)例成員、私有靜態(tài)成員、公有靜態(tài)成員和靜態(tài)類(lèi)的封裝。這次我們來(lái)討論一下面向?qū)ο蟪绦蛟O(shè)計(jì)中的另外兩個(gè)要素:繼承與多態(tài)。
2009-12-12 
js面向?qū)ο?多種創(chuàng)建對(duì)象方法小結(jié)
js面向?qū)ο?多種創(chuàng)建對(duì)象方法小結(jié),需要的朋友可以參考下
2012-05-05