練習用的 REPL
class Person {
get name() {return this._name;}
set name(arg) {this._name = arg;} // setter
get id() {return this._id;}
set id(arg) {this._id = arg;} // setter
}
呼叫端可以會直接指定 ID。
const martin = new Person();
martin.name = "martin";
martin.id = "1234"; // 使用了 setter
但 ID 應該在物件建立後,就不允許修改。
class Person {
constructor(id) {
this.id = id;
}
get name() {return this._name;}
set name(arg) {this._name = arg;}
get id() {return this._id;}
set id(arg) {this._id = arg;}
}
當可以使用建構子來傳遞 ID 後。
const martin = new Person("1234");
martin.name = "martin";
martin.id = "1234";
ID 的 setter 就可以刪除了。
class Person {
constructor(id) {
this.id = id;
}
get name() {return this._name;}
set name(arg) {this._name = arg;}
get id() {return this._id;}
// set id(arg) {this._id = arg;} // 移除 setter
}