ජාවාස්ක්රිප්ට් හි 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'),
];
වස්තු අරාව චක්රයකින් පුරා ගොස් කොන්සෝලයේ සේවකයින්ගේ නම් පමණක් මුද්රණය කරන්න.