紀錄工作經驗、相關知識,解決技術相關問題。

Javascript

JS instanceof:判斷物件是否為某類別的實例

JS instanceof:判斷物件是否為某類別的實例 特色圖片

JS instanceof 是二元運算子,用來檢查某個建構函式的 prototype 屬性,有沒有出現在物件的原型鏈上,回傳布林值。一般用法是判斷物件是不是由某個建構函式或 class 建立的實例。

function Car(make, model, year) {
  this.make = make;
  this.model = model;
  this.year = year;
}
const auto = new Car("Honda", "Accord", 1998);

console.log(auto instanceof Car);      // true
console.log(auto instanceof Object);   // true

auto 是用 Car 建立的,所以對 Car 是 true;所有物件的原型鏈最後都會接到 Object.prototype,所以對 Object 也是 true。

語法

object instanceof constructor

依 MDN 說明,左邊的 object 是優先順序在 9(關係運算子)以上的運算式,右邊的 constructor 是優先順序在 10(位元位移)以上的運算式,內容必須是建構函式,或是有 [Symbol.hasInstance]() 方法的物件。

右邊不是物件時,會丟出 TypeError;右邊沒有 [Symbol.hasInstance]() 方法時,也必須是函式,否則同樣丟出 TypeError:

try {
  ({}) instanceof 5;
} catch (e) {
  console.log(e.name);   // "TypeError"
}

try {
  ({}) instanceof {};
} catch (e) {
  console.log(e.name);   // "TypeError"
}

判斷方式:看原型鏈

instanceof 檢查的是 constructor.prototype 有沒有在 object 的原型鏈上。通常這代表 object 是用 constructor 建立的,但 MDN 指出並不是一定如此。

function C() {}
function D() {}

const o = new C();

console.log(o instanceof C);        // true
console.log(o instanceof D);        // false
console.log(o instanceof Object);   // true

o 的原型是 C.prototype,所以對 C 是 true;D.prototype 不在 o 的原型鏈上,所以對 D 是 false。

結果可能在物件建立之後改變。重新指定建構函式的 prototype,或用 Object.setPrototypeOf() 改物件的原型,都會影響判斷,MDN 說明這類做法通常不建議:

function C() {}
function D() {}

const o = new C();

C.prototype = {};            // 重新指定 prototype
const o2 = new C();

console.log(o2 instanceof C);   // true
console.log(o instanceof C);    // false:C.prototype 已不在 o 的原型鏈上

D.prototype = new C();
const o3 = new D();

console.log(o3 instanceof D);   // true
console.log(o3 instanceof C);   // true:C.prototype 在 o3 的原型鏈上

class 與繼承

class 也有 prototype 屬性,所以規則相同。子類別的實例,對自己和父類別都是 true:

class A {}
class B extends A {}

const o1 = new A();
console.log(o1 instanceof A);   // true
console.log(o1 instanceof B);   // false

const o2 = new B();
console.log(o2 instanceof A);   // true
console.log(o2 instanceof B);   // true

陣列與函式也是物件,可以對內建建構函式判斷:

console.log([] instanceof Array);            // true
console.log([] instanceof Object);           // true
console.log((() => {}) instanceof Function); // true
console.log((() => {}) instanceof Object);   // true

原始值永遠是 false

字串、數字這類原始值不是物件,instanceof 的結果是 false;用 new String() 建立的字串物件才是 true:

const literalString = "This is a literal string";
const stringObject = new String("String created with constructor");

console.log(literalString instanceof String);   // false
console.log(stringObject instanceof String);    // true

console.log(literalString instanceof Object);   // false
console.log(stringObject instanceof Object);    // true

console.log(stringObject instanceof Date);      // false

所以要判斷原始值的型別,請用 typeof(見下一節)。

instanceof 與 typeof 的差別

兩者回答的問題不同:

比較項目typeofinstanceof
回傳型別名稱的字串布林值
適合判斷原始值的型別物件是否屬於某個建構函式
物件的結果多半是 "object"可以區分 Array、Date、Map 等
原始值"string"、"number" 等一律 false
console.log(typeof []);                   // "object"
console.log([] instanceof Array);         // true

console.log(typeof new Date());           // "object"
console.log(new Date() instanceof Date);  // true

console.log(typeof "abc");                // "string"
console.log("abc" instanceof String);     // false

typeof 的各種回傳值,請參考 typeof 的語法文。

用 Object.create() 建立的物件

用 Object.create() 指定原型的物件,一樣依原型鏈判斷:

function Shape() {}

function Rectangle() {
  Shape.call(this);
}

Rectangle.prototype = Object.create(Shape.prototype);
Rectangle.prototype.constructor = Rectangle;

const rect = new Rectangle();

console.log(rect instanceof Object);      // true
console.log(rect instanceof Shape);       // true
console.log(rect instanceof Rectangle);   // true
console.log(rect instanceof String);      // false

原型是 null 的物件,原型鏈上沒有 Object.prototype,所以對 Object 是 false:

const literalObject = {};
const nullObject = Object.create(null);
nullObject.name = "My object";

console.log(literalObject instanceof Object);   // true
console.log(nullObject instanceof Object);      // false

判斷「不是實例」要加括號

要判斷物件不是某個建構函式的實例,要把整個 instanceof 運算式用括號包起來再加 !:

function Car(make, model, year) {
  this.make = make;
  this.model = model;
  this.year = year;
}
const myCar = new Car("Honda", "Accord", 1998);

console.log(!(myCar instanceof Car));   // false
console.log(!myCar instanceof Car);     // false,但意思不同

第二行的 !myCar 會先計算,得到布林值,變成在問「布林值是不是 Car 的實例」,結果永遠是 false,MDN 把它列為錯誤寫法。

用 Symbol.hasInstance 自訂判斷

右邊的建構函式如果有 Symbol.hasInstance 方法,instanceof 會優先呼叫它,傳入左邊的物件,this 是建構函式。

class Forgeable {
  static isInstanceFlag = Symbol("isInstanceFlag");

  static [Symbol.hasInstance](obj) {
    return Forgeable.isInstanceFlag in obj;
  }
}

const obj = { [Forgeable.isInstanceFlag]: true };

console.log(obj instanceof Forgeable);   // true

範例中的普通物件只要帶有特定旗標屬性,就會被判斷成這個 class 的實例。

函式預設都繼承 Function.prototype[Symbol.hasInstance](),所以右邊是一般函式時,通常是由它決定 instanceof 的行為。Symbol.hasInstance 的完整演算法請參考 Symbol 的語法文與 MDN 的 Symbol.hasInstance 頁面。

instanceof 為 true 不代表是用該建構函式建立的

MDN 指出,一個常見的誤解是 x instanceof C 為 true,就代表 x 是用 C 建立的。其實 x 也可以直接把 C.prototype 指定成原型,這時如果程式碼要讀取 C 的私有欄位,仍然會失敗:

class C {
  #value = "foo";
  static getValue(x) {
    return x.#value;
  }
}

const x = { __proto__: C.prototype };

if (x instanceof C) {
  try {
    C.getValue(x);
  } catch (e) {
    console.log(e.name);   // "TypeError"
  }
}

要避免這個情況,可以在 class 加上 Symbol.hasInstance,用 in 檢查私有欄位:

class C {
  #value = "foo";

  static [Symbol.hasInstance](x) {
    return #value in x;
  }
}

console.log({ __proto__: C.prototype } instanceof C);   // false
console.log(new C() instanceof C);                      // true

補充說明:子類別會繼承父類別的 Symbol.hasInstance,可能造成誤判。MDN 的做法是在方法裡加上 this === C,限制只對目前這個 class 生效。

跨 realm 的限制

JavaScript 的執行環境(視窗、frame 等)各自屬於獨立的 realm,各有自己的內建物件與全域物件,建構函式也不同。所以從另一個 realm 傳來的陣列,對目前環境的 Array 做 instanceof 會是 false,因為兩邊的 Array.prototype 不是同一個。

MDN 以 [] instanceof window.frames[0].Array 為例。下面用 Node.js 的 node:vm 模組建立另一個 realm 來示範同樣的情況:

const vm = require("node:vm");

const OtherArray = vm.runInNewContext("Array");
const otherArr = vm.runInNewContext("[]");

console.log([] instanceof OtherArray);    // false
console.log(otherArr instanceof Array);   // false
console.log(Array.isArray(otherArr));     // true

要確認某個值是不是陣列,不論它來自哪個 realm,MDN 建議用 Array.isArray()。

注意事項

  1. 原始值一律是 false:判斷原始值型別請用 typeof。
  2. 看的是原型鏈:改了 prototype 或物件的原型,結果會跟著變。
  3. 否定要加括號:!(a instanceof B),不是 !a instanceof B。
  4. 右邊必須是建構函式或有 Symbol.hasInstance 的物件:否則丟出 TypeError。
  5. 跨 realm 不可靠:陣列請改用 Array.isArray()。
  6. 原型為 null 的物件:對 Object 是 false。

支援版本

依 MDN 瀏覽器相容性資料(browser-compat-data 8.1.10,查詢日期 2026-11-24):instanceof 從 Chrome 1、Edge 12、Firefox 1、Safari 1 開始支援,Node.js 從 0.10.0 開始,Deno 從 1.0 開始,Internet Explorer 從 5 開始。

補充說明:範例在 Node.js 執行。MDN 的範例是原型鏈、class、原始值與字串物件、Object.create()、否定的括號寫法、Symbol.hasInstance 與私有欄位;與 typeof 的對照表與跨 realm 範例,是依 MDN 的說明另外示範的,跨 realm 範例用 Node.js 的 node:vm 取代瀏覽器的 frame。

參考資料與延伸閱讀

發佈留言