๐ธ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