javascript中類的定義方式詳解(四種方式)
本文實(shí)例講述了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();
定義了一個(gè)能創(chuàng)建并返回特定類型對(duì)象的工廠函數(shù), 看起來還是不錯(cuò)的, 但有個(gè)小問題 ,
每次調(diào)用時(shí)都要?jiǎng)?chuàng)建新函數(shù) showColor,我們可以把它移到函數(shù)外面,
function getName(){
document.write(this.name+"-----"+this.color+"<br>");
}
在工廠函數(shù)中直接指向它
這樣避免了重復(fù)創(chuàng)建函數(shù)的問題,但看起來不像對(duì)象的方法了。
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)建對(duì)象,而是使用 this 關(guān)鍵字。
使用 new 調(diào)用構(gòu)造函數(shù)時(shí),先創(chuàng)建了一個(gè)對(duì)象,然后用 this 來訪問。
這種用法于其他面向?qū)ο笳Z言很相似了, 但這種方式和上一種有同一個(gè)問題, 就是重復(fù)創(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)點(diǎn):
a. 所有實(shí)例存放的都是指向 showColor 的指針,解決了重復(fù)創(chuàng)建函數(shù)的問題
b. 可以用 instanceof 檢查對(duì)象類型
缺點(diǎn),添加下面的代碼:
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 對(duì)象的指針,proCar 的兩個(gè)實(shí)例都指向同一個(gè)數(shù)組。
4、動(dòng)態(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("動(dòng)態(tài)原型","yellow","1234565");
car4.getName();
car4.drives.push("newOne");
document.write(car4.drives);
這種方式是我最喜歡的, 所有的類定義都在一個(gè)函數(shù)中完成, 看起來非常像其他語言的類定義,不會(huì)重復(fù)創(chuàng)建函數(shù),還可以用 instanceof
希望本文所述對(duì)大家JavaScript程序設(shè)計(jì)有所幫助。
相關(guān)文章
javascript中不易分清的slice,splice和split三個(gè)函數(shù)
這篇文章主要為大家詳細(xì)介紹了javascript中不易分清的slice,splice和split三個(gè)函數(shù),感興趣的小伙伴們可以參考一下2016-03-03
BootstrapTable與KnockoutJS相結(jié)合實(shí)現(xiàn)增刪改查功能【二】
這篇文章主要介紹了BootstrapTable與KnockoutJS相結(jié)合實(shí)現(xiàn)增刪改查功能【二】的相關(guān)資料,非常具有參考價(jià)值,感興趣的朋友一起學(xué)習(xí)吧2016-05-05
javascript制作游戲開發(fā)碰撞檢測(cè)的封裝代碼
這篇文章主要介紹了javascript制作游戲開發(fā)碰撞檢測(cè)的封裝代碼,需要的朋友可以參考下2015-03-03

