Getter 跟 Setter 可視為物件的特殊方法,以類似讀取屬性(property)的方式,隱藏背後呼叫方法
js 本身也有內建的 getter & setter
像 nameOfArray.length
(getter), nameOfMap.size
(getter)
如何分辨該方法是 Getter & Setter?
()
呼叫Getter & Setter 有其特殊優勢,諸如:
以下為 getter & setter 示例
getter 用於計算該方形物件面積
setter 用於驗證傳入建立方形的數值為有效值
class RectTangle {
constructor(width, height) {
this.width = width;
this.height = height;
}
set width(value) {
if (value <= 0) {
throw new Error("invalid value of width");
}
this._width = value;
}
set height(value) {
if (value <= 0) {
throw new Error("invalid value of height");
}
this._height = value;
}
get area() {
return this._width * this._height;
}
}
try {
let invalidRectangle = new RectTangle(10, -12);
} catch (error) {
console.log(error.message);
}
Math.floor()
, Math.random()
, Array.from()
都是靜態方法Object.keys(nameOfObjectInstance)
, Object.entries(nameOfObjectInstance)
forEach()
, map()
innerWidth
, onload
實際上省略掉 window object
,所以它們是 instance methodisNaN
, isFinite
, console.log()