🔸getter/setter
JS ⟩ class ⟩ definition ⟩ getters/setters
class User {
constructor(name) {
this.name = name; // ⭐ invokes "setter"❗
}
// ⭐ getter: access `this.name`
get name() {
return this._name;
}
// ⭐ setter: set `this.name` (this.name = ...)
set name(value) {
// guard length >= 4
if (value.length < 4) {
log("name too short."); return;
}
this._name = value; // private property
}
}
// test code
let user = new User('Mary');
// ⭐ invokes "setter":
user.name = 'Joe'; // "name too short."
// ⭐ invokes "getter":
log(user.name); // "Mary"
⭐️ 注意:getter 不能這樣寫❗️
// ⛔ SyntaxError: Unexpected token 'function'
// vvvvvvvv
Array.prototype.maxRowLength = get function(){
return Math.max(...this.map(row => row.length))
}
differences between getter and Object.defineProperty() :
the getter is defined on the instance's prototype,
with
Object.defineProperty()
the property is defined on the instance.
Object.defineProperty()
Object.defineProperties()
object getter/setter
behaves like class field (instance property).
Google Apps Script 目前不支援 class field,但可用 (static/instance) getter/setter 代替。
[[Get]]/[[Set]] is used internally in mixin by Object.assign().
Archive
replit ⟩ getter & setter
const {log} = console;
/* -------------- new object -------------- */
const expr = 'foo';
const obj = {
// obj.log ↱ ⭐️ 注意:有 ","
log: ['example','test'],
// ⭐️ getter (obj.latest)
get latest() {
return this.log[this.log.length - 1];
},
// ⭐️ getter (obj.foo)
get [expr]() { return 'bar' } // ⭐️ computed property name
};
/* -------------- existing object -------------- */
const o = {a: 0};
// ⭐️ o.b ↱ ⭐️ property name
Object.defineProperty(o, 'b', {
get: function() { return this.a + 1 }
});
// ⭐️ p.name (= name)
// ↱ ⭐️ (same) object passed in ↰
const p = Object.defineProperties({ }, {
// ↱ ⭐️ property name
name: { // ↱ ⭐️ 注意:有 ","
set(name) { this._name = name.toLowerCase(); },
get() { return this._name; }
},
});
p.name = 'MoLLy BroWn'; // ⭐️ setter
/* -------------- class definition -------------- */
class MyArray extends Array {
// ⭐️ instance getters ↱ ⭐️ 注意:沒有 ","
get first() { return this[0] } // arr.first
get last() { return this[this.length - 1] } // arr.last
// ⭐️ static getter
static get foo() { return 'foo' } // ⭐️ MyArray.foo
}
/* -------------- log -------------- */
const arr = new MyArray('a', 'b', 'c', 'd');
[
obj.latest, // 'test'
obj.foo, // 'bar'
o.b, // 1
p.name, // "molly brown"
arr.last, // "d"
arr.push('e'), // 5 (⭐️ new length)
arr.last, // "e"
MyArray.foo, // 'foo'
].forEach(x => log(x));
Last updated