您好,登錄后才能下訂單哦!
這篇文章將為大家詳細講解有關JavaScript如何手動實現(xiàn)instanceof,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。
instanceof
運算符用于檢測構(gòu)造函數(shù)的prototype
屬性是否出現(xiàn)在某個實例對象的原型鏈上。
function Person() {} function Person2() {} const usr = new Person(); console.log(usr instanceof Person); // true console.log(usr instanceof Object); // true console.log(usr instanceof Person2); // false
如上代碼,定義了兩個構(gòu)造函數(shù),Person
和Person2
,又實用new
操作創(chuàng)建了一個Person
的實例對象usr
。
實用instanceof
操作符,分別檢驗構(gòu)造函數(shù)的prototype
屬性是否在usr
這個實例的原型鏈上。
當然,結(jié)果顯示,Person
和Object
的prototype
屬性在usr
的原型鏈上。usr
不是Person2
的實例,故Person2
的prototype
屬性不在usr
的原型鏈上。
明白了instanceof
的功能和原理后,可以自己實現(xiàn)一個instanceof
同樣功能的函數(shù):
function myInstanceof(obj, constructor) { // obj的隱式原型 let implicitPrototype = obj?.__proto__; // 構(gòu)造函數(shù)的原型 const displayPrototype = constructor.prototype; // 遍歷原型鏈 while (implicitPrototype) { // 找到,返回true if (implicitPrototype === displayPrototype) return true; implicitPrototype = implicitPrototype.__proto__; } // 遍歷結(jié)束還沒找到,返回false return false; }
myInstanceof
函數(shù)接收兩個參數(shù):實例對象obj
和構(gòu)造函數(shù)constructor
。
首先拿到實例對象的隱式原型:obj.__proto__
,構(gòu)造函數(shù)的原型對象constructor.prototype
。
接著,就可以通過不斷得到上一級的隱式原型:
implicitPrototype = implicitPrototype.__proto__;
來遍歷原型鏈,尋找displayPrototype
是否在原型鏈上,若找到,返回true
。
當implicitPrototype
為null
時,結(jié)束尋找,沒有找到,返回false
。
原型鏈其實就是一個類似鏈表的數(shù)據(jù)結(jié)構(gòu)。
instanceof
做的事,就是在鏈表上尋找有沒有目標節(jié)點。從表頭節(jié)點開始,不斷向后遍歷,若找到目標節(jié)點,返回true
。遍歷結(jié)束還沒找到,返回false
。
寫一個簡單的實例驗證一下自己實現(xiàn)的instanceof
:
function Person() {} function Person2() {} const usr = new Person(); function myInstanceof(obj, constructor) { let implicitPrototype = obj?.__proto__; const displayPrototype = constructor.prototype; while (implicitPrototype) { if (implicitPrototype === displayPrototype) return true; implicitPrototype = implicitPrototype.__proto__; } return false; } myInstanceof(usr, Person); // true myInstanceof(usr, Object); // true myInstanceof(usr, Person2); // false myInstanceof(usr, Function); // false myInstanceof(usr.__proto__, Person); // false usr.__proto__ instanceof Person; // false
可以看到,myInstanceof
正確得出了結(jié)果。
關于“JavaScript如何手動實現(xiàn)instanceof”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,使各位可以學到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。