JavaScriptのOOPにおける仮想プロパティのゲッター
アクセッサを使用することで、実際にはオブジェクト内に存在しない仮想プロパティを作成することができます。例を見てみましょう。2つのパブリックプロパティを持つクラスがあるとします:
class User {
constructor(name, surn) {
this.name = name;
this.surn = surn;
}
}
名前と姓を含む3つ目のプロパティを作成してみましょう。そのために、アクセッサプロパティを作成します:
class User {
constructor(name, surn) {
this.name = name;
this.surn = surn;
}
get full() {
return this.name + ' ' + this.surn;
}
}
確認してみましょう。名前と姓をパラメータとして渡して、クラスのオブジェクトを作成します:
let user = new User('john', 'smit');
パブリックプロパティの値を出力します:
console.log(user.name); // 'john'
console.log(user.surn); // 'smit'
次に、仮想プロパティの値を出力します:
console.log(user.full); // 'john smit'