JavaScript-da OOP-da instanceof operatori
instanceof operatori obyektning ma'lum bir classga tegishli ekanligini tekshirish imkonini beradi.
Keling, bir misolni ko'rib chiqaylik. Faraz qilaylik, bizda quyidagi class mavjud:
class User {
}
Ushbu classdan obyekt yaratamiz:
let user = new User;
O'zgaruvchidagi obyekt bizning classimizga tegishli ekanligini teksiramiz:
console.log(user instanceof User); // true
Quyidagi kodni bajarish natijasi qanday bo'lishini aniqlang:
class Student {
}
class Employee {
}
let employee = new Employee;
console.log(employee instanceof Employee);
console.log(employee instanceof Student);
Quyidagi kod berilgan:
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'),
];
Obyektlar massivini tsikl yordamida aylantiring va faqat xodimlarning ismlarini konsolga chiqaring.