JavaScript'te OOP'de instanceof Operatörü
instanceof operatörü, bir nesnenin
belirli bir sınıfa ait olup olmadığını kontrol etmeye
yarar. Bir örnek üzerinden inceleyelim. Aşağıdaki
sınıfımız olsun:
class User {
}
Bu sınıftan bir nesne oluşturalım:
let user = new User;
Değişkendeki nesnenin bizim sınıfımıza ait olup olmadığını kontrol edelim:
console.log(user instanceof User); // true
Aşağıdaki kodun çalıştırılmasının sonucunun ne olacağını belirleyin:
class Student {
}
class Employee {
}
let employee = new Employee;
console.log(employee instanceof Employee);
console.log(employee instanceof Student);
Aşağıdaki kod verilmiştir:
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'),
];
Nesne dizisini bir döngü ile gezin ve sadece çalışanların isimlerini konsola yazdırın.