Javascript中定義類(class)的幾種方法總結
來源:程序員人生 發布時間:2013-11-28 12:37:39 閱讀次數:3302次
方法一:工廠方式--- 創建并返回特定類型的對象的 工廠函數 ( 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;
}
方法二:構造函數方式--- 構造函數看起來很像工廠函數
function Car(color,doors,mpg){
this.color = color;
this.doors = doors;
this.mpg = mpg;
this.showCar = function(){
alert(this.color);
};
}
方法三:原型方式--- 利用了對象的 prototype 屬性,可把它看成創建新對象所依賴的原型
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);
};
方法四:混合的構造函數 /原型方式--- 用構造函數定義對象的所有非函數屬性,用原型方式定義對象的函數屬性(方法)
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);
};
方法五:動態原型方法--- 在構造函數內定義非函數屬性,而函數屬性則利用原型屬性定義。唯一的區別是賦予對象方法的位置。
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;
}
}
//該方法使用標志( _initialized )來判斷是否已給原型賦予了任何方法。
利用原型prototype。 function Bar(text, url) {
this.text = text;
this.url = url;
}
Bar.prototype = {
render : function() {
document.write('<a href="' + this.url + '">' + this.text + '</a>');
}
}
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈