判斷型別時,很多人第一個想到 typeof。但只要值是參考類型,它就會全部回傳 "object",完全分不出是陣列、日期還是自訂物件。這時候就需要 instanceof。
instanceof 用來判斷某個物件是不是另一個物件的實例,也就是檢查它是否屬於某種類型。
更有價值的是,它可以用來判斷一個實例是否屬於它的父類型——這在處理繼承體系時非常實用。
function Aoo(){}
function Foo(){}
Foo.prototype = new Aoo(); // JavaScript 原型繼承
var foo = new Foo();
console.log(foo instanceof Foo); // true
console.log(foo instanceof Aoo); // true
單層繼承如此,多層繼承同樣適用:instanceof 會沿著原型鏈一路往上找,只要鏈上出現過該建構函式的 prototype,就回傳 true。
function Cat(){}
Cat.prototype = {};
function Dog(){}
Dog.prototype = {};
var dog1 = new Dog();
alert(dog1 instanceof Dog); // true
alert(dog1 instanceof Object); // true
Dog.prototype = Cat.prototype;
alert(dog1 instanceof Dog); // false
alert(dog1 instanceof Cat); // false
alert(dog1 instanceof Object); // true
var dog2 = new Dog();
alert(dog2 instanceof Dog); // true
alert(dog2 instanceof Cat); // true
alert(dog2 instanceof Object); // true
Dog.prototype = null;
var dog3 = new Dog();
alert(dog3 instanceof Cat); // false
alert(dog3 instanceof Object); // true
alert(dog3 instanceof Dog); // error
這幾段之所以看起來撓人,關鍵在於:instanceof 判斷的對象是實例的內部原型鏈,而 dog1 的原型鏈在建立時就固定了,之後改動 Dog.prototype 並不會回溯影響已存在的實例。只有新建的 dog2 才會走上新的原型鏈。最後把 prototype 設為 null 更是直接讓判斷拋錯。
一是語言規範中對這個運算符的定義,二是 JavaScript 的原型繼承機制。理解 __proto__、prototype 與 constructor 三者的關係之後,上面那些「為什麼」都會變成理所當然。
實務上判斷陣列用 Array.isArray(),判斷完整型別用 Object.prototype.toString.call(value),都比 instanceof 更穩。因為 instanceof 在跨 iframe、跨 realm 的場景下會失效——不同視窗的同名建構函式並不是同一個函式。