- 相關(guān)推薦
Javascript自定義類(lèi)型的幾種方法小結
1. 定義類(lèi)型
復制代碼 代碼如下:
function UserObject(parameter) {
}
parameter 可省略,相當于C#中構造函數參數。
2. 實(shí)例化自定義類(lèi)型
復制代碼 代碼如下:
function userobject(parameter){
}
//myobject is now an object of type userobject!
var myobject=new userobject("hi")
alert(myobject)
3. 添加屬性
復制代碼 代碼如下:
function userobject(parameter){
this.firstproperty=parameter
this.secondproperty="This is the second property"
}
//使用
復制代碼 代碼如下:
var myobject=new userobject("hi there.")
//alerts "hi there."
alert(myobject.firstproperty)
//writes "This is the second property"
document.write(myobject.secondproperty)
4.添加方法 (circle類(lèi))
復制代碼 代碼如下:
//first method function
function computearea(){
var area=this.radius*this.radius*3.14
return area
}
//second method function
function computediameter(){
var diameter=this.radius*2
return diameter
}
關(guān)聯(lián)到自定義類(lèi)型:
復制代碼 代碼如下:
/*the below creates a new object, and gives it the two methods defined earlier*/
function circle(r){
//property that stores the radius
this.radius=r
this.area=computearea
this.diameter=computediameter
}
使用自定義方法:
復制代碼 代碼如下:
var mycircle=new circle(20)
//alerts 1256
alert("area="+mycircle.area())
//alerts 400
alert("diameter="+mycircle.diameter())
【Javascript自定義類(lèi)型的幾種方法小結】相關(guān)文章:
JavaScript常用方法匯總10-25
關(guān)于數據類(lèi)型的Javascript學(xué)習筆記08-05
街舞有幾種類(lèi)型05-05
公文類(lèi)型有幾種06-29
JavaScript數組常用方法介紹09-04
javascript跨域訪(fǎng)問(wèn)的方法07-09
javascript編程異常處理的方法08-04