JavaScriptにおけるOOPのクラス内オブジェクト
クラス内で他のクラスのオブジェクトを 使用することができます。 例を見てみましょう。 名前と姓、および居住都市を持つ ユーザーを作成したいとします。 次のような都市用のクラスがあるとします:
class City {
constructor(name) {
this.name = name;
}
}
名前、姓、都市をコンストラクタの パラメータとして渡すことにします:
class User {
constructor(name, surn, city) {
this.name = name;
this.surn = surn;
this.city = city;
}
}
この場合、名前と姓は文字列ですが、 都市は別個のクラスのオブジェクトになります:
let city = new City('luis');
let user = new User('john', 'smit', city);
ユーザーの名前を出力してみましょう:
console.log(user.name);
次に、ユーザーの都市名を出力してみましょう:
console.log(user.city.name);
次のクラスが与えられています:
class Employee {
constructor(name, position, department) {
this.name = name;
this.position = position;
this.department = department;
}
}
2番目と3番目のパラメータに、 別個のクラスのオブジェクトが渡されるようにしてください。
前のタスクのクラスを使用して、 従業員オブジェクトを作成してください。
作成した従業員の名前、役職、 および部署をコンソールに出力してください。