如何在JavaScript中建立自己的物件
在JavaScript中建立自己的物件可以遵循這兩個步驟[1]:
1. 使用方法宣告物件。
2. 使用 “new" 關鍵字來建構新的物件。
[宣告]
例如: 建立一個 userobject 物件
step 1:
function userobject(parameter){
}
parameter 並不是必需的。
上面的程式碼,在本質上,我們建立了一個新物件名稱為 “userobject"。把它稱為類別可能比較恰當。
[建立]
step 2:
定義好了之後,我們可以使用"new"來建構物件並且使用它。
<script type="text/javascript">
function userobject(parameter){
}
//myobject is now an object of type userobject!
var myobject=new userobject(“hi")
</script>
在這裡,myobject 是一個物件,這個物件是 userobject 的實體(instance)。
[屬性]
如何為物件新增屬性:在定義物件的方法中嵌入屬性,每個屬性的前面使用關鍵字 this 加上一點(.)。例如:我們擴展(extend) userobject來包含兩個屬性:
function userobject(parameter){
this.firstproperty=parameter
this.secondproperty="This is the second property"
}
使用範例:
<script>
var myobject=new userobject(“hi there.")
//alerts “hi there."
alert(myobject.firstproperty)
//writes “This is the second property"
document.write(myobject.secondproperty)
</script>
[方法]
如何為物件新增方法:首先,為每一個方法宣告並且定義函數(稱為 method function),然後再把它與方法關連起來。例如:
//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
}
那麼,這句話是什麼意思呢?尤其是那個this
var area=this.radius*this.radius*3.14
解釋:一個 method function最終會跟物件關連起來,所以,method function 可以存取物件的屬性。
現在,我們可以將 method function 與方法關連起來了,例如:
<script type="text/javascript">
/*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
}
</script>
[測試]
<script type="text/javascript">
var mycircle=new circle(20)
//alerts 1256
alert(“area="+mycircle.area())
//alerts 400
alert(“diameter="+mycircle.diameter())
</script>
參考: