JavaScriptのOOPにおけるinstanceof演算子
演算子 instanceof は、オブジェクトが特定のクラスに属しているかどうかをチェックすることができます。
例を見てみましょう。次のクラスがあるとします:
class User {
}
このクラスからオブジェクトを作成します:
let user = new User;
変数内のオブジェクトが私たちのクラスに属しているかどうかを確認します:
console.log(user instanceof User); // true
次のコードを実行した結果がどうなるか、決定してください:
class Student {
}
class Employee {
}
let employee = new Employee;
console.log(employee instanceof Employee);
console.log(employee instanceof Student);
次のコードが与えられています:
class Student {
constructor(name) {
this.name = name;
}
}
class Employee {
constructor(name) {
this.name = name;
}
}
let users = [
new Student('user1'),
new Employee('user2'),
new Student('user3'),
new Employee('user4'),
new Student('user5'),
new Employee('user6'),
new Student('user7'),
];
オブジェクトの配列をループで回し、コンソールに従業員の名前だけを出力してください。