Javascript初學筆記9 Getter & Setter

這應該是目前JS我接觸到最陌生的觀念了,即便反覆看了幾次相關的文章也做了練習
現階段的我還是無法完全理解這兩者的目的以及優勢,我們先看一下以下的範例,最後再總結我目前的理解。

const robot = {
_model: '1E78V2',
_energyLevel: 100,
_numOfSensors: 15,
get numOfSensors(){
if(typeof this._numOfSensors === 'number'){
return this._numOfSensors;
} else {
return 'Sensors are currently down.'
}
},
set numOfSensors(num){
if (typeof num === 'number' && num >=0 ){
this._numOfSensors = num
} else {
console.log('Pass in a number that is greater than or equal to 0')
}
}
};
robot.numOfSensors // 15
robot.numOfSensors = 100
console.log(robot.numOfSensors) // 100


我們看一下上方的程式碼,首先我們宣告了名為robot的物件,其中包含了三組key-value pair以及兩個陌生的function getter & setter,先從get numOfSensors 開始說明。
在這個函數中我們使用了關鍵字 get ,用get建立的函數可以方便我們存取物件中的內容,與單純建立function的差別最明顯就是呼叫時不需要使用()。
另一方面關鍵字 set 則是在物件中建立一個用來修改變數的函數,特別注意使用時還是採用一般存入新變數的方法 而不是numOfSensors(100) <=這個寫法會回傳錯誤。

getter & setter 有幾個注意事項

  • 一個物件內僅能有一個getter/setter,兩個以上時會出現錯誤
  • 要刪除getter/setter時可以利用delete

最後做個簡單的總結,使用getter/setter的目的光看上方的範例會看不出來,目前我的理解是為了程式的封裝,不讓外部的使用者直接存取/修改物件內的數值,當一個物件內存在著getter&setter,便只能利用getter取值 setter賦值,直接的存取則會回傳錯誤。

發表留言