JavaScriptのOOPにおける仮想プロパティのセッター
仮想プロパティのゲッターに加えて、 そのセッターも作成できます。 この場合、セッター内でデータを取得し、 分割して、対応する部分を適切な 公開プロパティに書き込む必要があります。
試してみましょう。仮想プロパティ
fullのセッターを実装します:
class User {
constructor(name, surn) {
this.name = name;
this.surn = surn;
}
get full() {
return this.name + ' ' + this.surn;
}
set full(full) {
let [name, surn] = full.split(' ');
this.name = name;
this.surn = surn;
}
}
分割代入を簡略化します:
class User {
constructor(name, surn) {
this.name = name;
this.surn = surn;
}
get full() {
return this.name + ' ' + this.surn;
}
set full(full) {
[this.name, this.surn] = full.split(' ');
}
}
クラスのオブジェクトを作成します:
let user = new User('john', 'smit');
仮想セッターにデータを書き込みます:
user.full = 'eric jons';
オブジェクトのプロパティが変更されたことを 確認します:
console.log(user.name); // 'eric'
console.log(user.surn); // 'jons'
console.log(user.full); // 'eric jons'