ตัวดำเนินการ instanceof ใน OOP ใน JavaScript

ตัวดำเนินการ instanceof ช่วยให้ตรวจสอบได้ว่า วัตถุนั้นเป็นของคลาสเฉพาะหรือไม่ มาดูตัวอย่างกัน สมมติว่าเรามี คลาสต่อไปนี้:

javascriptclass User {
  
}

มาสร้างวัตถุจากคลาสนี้:

javascriptlet user = new User;

ตรวจสอบว่า วัตถุจาก ตัวแปรเป็นของคลาสของเราหรือไม่:

javascriptconsole.log(user instanceof User); // true
Задание 1

จงกำหนดว่าผลลัพธ์ จากการรันโค้ดต่อไปนี้จะเป็นอย่างไร:

javascriptclass Student {
  
}
class Employee {
  
}

let employee = new Employee;
console.log(employee instanceof Employee);
console.log(employee instanceof Student);
Задание 2

กำหนดโค้ดต่อไปนี้:

javascriptclass 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'),
];

วนลูปผ่านอาร์เรย์ของวัตถุ และแสดงในคอนโซลเฉพาะชื่อ ของพนักงานเท่านั้น