理解Javascript_07_理解instanceof實現原理
在《Javascript類型檢測》一文中講到了用instanceof來用做檢測類型,讓我們來回顧一下:
那么instanceof的這種行為到底是如何實現的呢,現在讓我們揭開instanceof背后的迷霧。
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_06_理解對象的創建過程》已經講解過了。
結論
根據代碼運行結果和內存結構,推導出結論:
instanceof 檢測一個對象A是不是另一個對象B的實例的原理是:查看對象B的prototype指向的對象是否在對象A的[[prototype]]鏈上。如果在,則返回true,如果不在則返回false。不過有一個特殊的情況,當對象B的prototype為null將會報錯(類似于空指針異常)。
這里推薦一篇文章,來自于歲月如歌,也是關于instanceof原理的,角度不同,但有異曲同工之妙。
http://lifesinger.org/blog/2009/09/instanceof-mechanism/