object instanceof Constructor // 回傳 boolean
語意:檢查 Constructor.prototype 是否存在於 object 的原型鏈上。與構造器函式本身無關,只看原型鏈。
function Person(name, age) { this.name = name; this.age = age; }
const p = new Person('John', 82);
console.log(p instanceof Person); // true
function A() {}
function B() {}
B.prototype = new A(); // B 繼承 A
const b = new B();
console.log(b instanceof A); // true
console.log(b instanceof B); // true
function A() {}
const a = new A();
console.log(a instanceof Object); // true
console.log('hello' instanceof Object); // false(字面值非物件)
console.log(new String('hello') instanceof Object); // true
console.log(new Number(1) instanceof Object); // true
function A() {}
console.log(A instanceof Function); // true
console.log(String instanceof Function); // true
console.log(Number instanceof Function); // true
若實例是由某類別或其子類別建立,instanceof 即回傳真。換句話說:構造函式的 prototype 存在於物件的內部原型鏈上,即返回 true。
function A() {}
function B() {}
A.prototype = B.prototype = { x: 1 };
const a = new A();
const b = new B();
console.log(a instanceof B); // true!因為 B.prototype 在 a 的原型鏈上
console.log(b instanceof A); // true!同理
function A() {}
const a = new A();
A.prototype = {}; // 重新指派 prototype
console.log(a instanceof A); // false!a 的原型鏈仍指向舊 prototype
此時 new A() 建立的新實例會指向新 prototype,但舊實例 a 不受影響。
V 非物件 → 回傳 false。(1 instanceof Object 為 false)F 的 prototype 屬性為 O;若 O 非物件 → 拋 TypeError。V = V.[[Prototype]];重複:V === null → 回傳 false。V === O → 回傳 true。Java 同樣遵循「實例屬於類別或其父類別」規則:
class Person { ... }
class Man extends Person { ... }
Man m = new Man();
m instanceof Man; // true
m instanceof Person; // true
m instanceof Object; // true
1 instanceof Number 永遠 false。[] instanceof Array 可能為 false。改用 Array.isArray() 或 Object.prototype.toString.call()。extends 會正確建構原型鏈,instanceof 行為符合預期。static [Symbol.hasInstance] 覆寫預設邏輯。掌握原型鏈機制,instanceof 就不再是黑盒,而是精準檢測物件關係的利器。