জাভাস্ক্রিপ্টের 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'),
];
অবজেক্টগুলোর অ্যারেটি লুপ দিয়ে ঘুরিয়ে শুধুমাত্র কর্মচারীদের নাম কনসোলে আউটপুট করুন।