那麼 instanceof 的這種行為究竟是如何實現的?現在讓我們揭開它背後的迷霧。
照慣例,先看一段代碼:
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
讓我們畫一張內存圖來分析:
內存圖比較複雜,解釋一下:程式本身是一個動態的概念,隨著程式執行,Dog.prototype 會不斷改變。為了方便,這裡用一張圖來表達這三次 prototype 引用的改變。在堆中,右邊是函數對象的內存表示,中間是函數對象 prototype 屬性的指向,左邊是函數對象創建的實例。其中函數對象指向 prototype 屬性的指針上標註了 dog1、dog2、dog3,分別對應 Dog.prototype 的三次引用改變,它們和棧中的 dog1、dog2、dog3 也有對應關係。
要特別注意,dog3 中函數對象的 prototype 屬性為 null,此時函數對象實例 dog3 的內部 [[prototype]] 屬性將指向 Object.prototype,這一點在《理解 JavaScript(六):理解對象的創建過程》中已經講解過了。
根據代碼運行結果和內存結構,可以推導出結論:instanceof 檢測一個對象 A 是不是另一個對象 B 的實例,其原理是——查看對象 B 的 prototype 所指向的對象,是否在對象 A 的 [[prototype]] 鏈上。如果在,返回 true;如果不在,返回 false。不過有一個特殊情況:當對象 B 的 prototype 為 null 時會報錯(類似空指針異常)。
這裡推薦一篇來自「歲月如歌」的文章,同樣是關於 instanceof 原理的,角度不同,卻有异曲同工之妙。