Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Toán tử instanceof trong JavaScript

instanceof kiểm tra property prototype của constructor có xuất hiện trong prototype chain của object không. Đơn giản: kiểm tra biến có phải kiểu nào đó.

Primitive

String, number là primitive, không có [[Prototype]]. Chỉ hoạt động nếu wrap trong object.

Ví dụ

console.log(1 instanceof Number);           // false
console.log(new Number(1) instanceof Number); // true
console.log("" instanceof String);           // false
console.log(new String("") instanceof String); // true

Constructor function (Class)

Function trả về object (JS Class) có thể check instance.

Ví dụ

function Person(name) { this.name = name; }
let john = new Person("John");
console.log(john instanceof Person); // true

Kế thừa (Inheritance)

JS prototype inheritance: check instanceof bất kỳ class nào trong hierarchy đều true.

Ví dụ

class Person {}
class Student extends Person {
  constructor(name) { super(); this.name = name; }
}
let john = new Student("John");
console.log(john instanceof Person);  // true
console.log(john instanceof Student); // true

Lưu ý: instanceof kiểm tra prototype chain, không phải constructor function trực tiếp. Có thể lừa: Object.setPrototypeOf(obj, SomeClass.prototype) làm obj instanceof SomeClass trả true. Cross-frame/iframe: constructor khác reference → instanceof fail.