javascript中類的定義方式詳解(四種方式)
本文實例講述了javascript中類的定義方式。分享給大家供大家參考,具體如下:
類的定義包括四種方式:
1、工廠方式
function createCar(name,color,price){
var tempcar=new Object;
tempcar.name=name;
tempcar.color=color;
tempcar.price=price;
tempcar.getName=function(){
document.write(this.name+"-----"+this.color+"<br>");
};
return tempcar;
}
var car1=new createCar("工廠桑塔納","red","121313");
car1.getName();
定義了一個能創(chuàng)建并返回特定類型對象的工廠函數(shù), 看起來還是不錯的, 但有個小問題 ,
每次調(diào)用時都要創(chuàng)建新函數(shù) showColor,我們可以把它移到函數(shù)外面,
function getName(){
document.write(this.name+"-----"+this.color+"<br>");
}
在工廠函數(shù)中直接指向它
這樣避免了重復創(chuàng)建函數(shù)的問題,但看起來不像對象的方法了。
2、構(gòu)造函數(shù)方式
function Car(name,color,price){
this.name=name;
this.color=color;
this.price=price;
this.getColor=function(){
document.write(this.name+"-----"+this.color+"<br>");
};
}
var car2=new Car("構(gòu)造桑塔納","red","121313");
car2.getColor();
可以看到與第一中方式的差別,在構(gòu)造函數(shù)內(nèi)部無創(chuàng)建對象,而是使用 this 關(guān)鍵字。
使用 new 調(diào)用構(gòu)造函數(shù)時,先創(chuàng)建了一個對象,然后用 this 來訪問。
這種用法于其他面向?qū)ο笳Z言很相似了, 但這種方式和上一種有同一個問題, 就是重復創(chuàng)建函數(shù)。
3、原型方式
function proCar(){
}
proCar.prototype.name="原型";
proCar.prototype.color="blue";
proCar.prototype.price="10000";
proCar.prototype.getName=function(){
document.write(this.name+"-----"+this.color+"<br>");
};
var car3=new proCar();
car3.getName();
首先定義了構(gòu)造函數(shù) Car,但無任何代碼,然后通過 prototype 添加屬性。優(yōu)點:
a. 所有實例存放的都是指向 showColor 的指針,解決了重復創(chuàng)建函數(shù)的問題
b. 可以用 instanceof 檢查對象類型
缺點,添加下面的代碼:
proCar.prototype.drivers = newArray("mike", "sue");
car3.drivers.push("matt");
alert(car3.drivers);//outputs "mike,sue,matt"
alert(car3.drivers);//outputs "mike,sue,matt"
drivers 是指向 Array 對象的指針,proCar 的兩個實例都指向同一個數(shù)組。
4、動態(tài)原型方式
function autoProCar(name,color,price){
this.name=name;
this.color=color;
this.price=price;
this.drives=new Array("mike","sue");
if(typeof autoProCar.initialized== "undefined"){
autoProCar.prototype.getName =function(){
document.write(this.name+"-----"+this.color+"<br>");
};
autoProCar.initialized=true;
}
}
var car4=new autoProCar("動態(tài)原型","yellow","1234565");
car4.getName();
car4.drives.push("newOne");
document.write(car4.drives);
這種方式是我最喜歡的, 所有的類定義都在一個函數(shù)中完成, 看起來非常像其他語言的類定義,不會重復創(chuàng)建函數(shù),還可以用 instanceof
希望本文所述對大家JavaScript程序設(shè)計有所幫助。
相關(guān)文章
javascript中不易分清的slice,splice和split三個函數(shù)
這篇文章主要為大家詳細介紹了javascript中不易分清的slice,splice和split三個函數(shù),感興趣的小伙伴們可以參考一下2016-03-03
BootstrapTable與KnockoutJS相結(jié)合實現(xiàn)增刪改查功能【二】
這篇文章主要介紹了BootstrapTable與KnockoutJS相結(jié)合實現(xiàn)增刪改查功能【二】的相關(guān)資料,非常具有參考價值,感興趣的朋友一起學習吧2016-05-05

