Instanceof Operator ทดสอบว่า Prototype Property ของ Constructor ปรากฏใน Prototype Chain ของ Object ไหม ภาษาเรียบๆ: ทดสอบว่า Variable เป็น Type ใด แต่มี Caveats มาดูตัวอย่าง
Primitives
Strings และ Numbers เป็น Primitive Values ไม่ใช่ Objects จึงไม่มี [[Prototype]] จึงทำงานได้ก็ต่อเมื่อ Wrap ใน Regular Objects
ตัวอย่าง
console.log(1 instanceof Number) console.log(new Number(1) instanceof Number) console.log("" instanceof String) console.log(new String("") instanceof String)
ผลลัพธ์
false true false true
Constructible Functions
Functions ที่ Return Objects ของตัวเอง (JS Classes) สามารถตรวจสอบ Objects ของพวกเขาด้วย Instanceof ได้
ตัวอย่าง
function Person(name) { this.name = name } let john = new Person("John"); console.log(john instanceof Person)
ผลลัพธ์
true
Inheritance
JS รองรับ Prototypical Inheritance หากเช็ค Instanceof สำหรับ Class ใดใน Hierarchy จะคืน True
ตัวอย่าง
class Person {} class Student extends Person { constructor(name) { super() this.name = name } } let john = new Student("John"); console.log(john instanceof Person) console.log(john instanceof Student)
ผลลัพธ์
true true