ตัวดำเนินการ instanceof ใน OOP ใน JavaScript
ตัวดำเนินการ 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'),
];
วนลูปผ่านอาร์เรย์ของวัตถุ และแสดงในคอนโซลเฉพาะชื่อ ของพนักงานเท่านั้น