JavaScript 手動實現(xiàn)instanceof的方法
1. instanceof的用法
instanceof運算符用于檢測構造函數(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
如上代碼,定義了兩個構造函數(shù),Person和Person2,又實用new操作創(chuàng)建了一個Person的實例對象usr。
實用instanceof操作符,分別檢驗構造函數(shù)的prototype屬性是否在usr這個實例的原型鏈上。
當然,結果顯示,Person和Object的prototype屬性在usr的原型鏈上。usr不是Person2的實例,故Person2的prototype屬性不在usr的原型鏈上。
2. 實現(xiàn)instanceof
明白了instanceof的功能和原理后,可以自己實現(xiàn)一個instanceof同樣功能的函數(shù):
function myInstanceof(obj, constructor) {
// obj的隱式原型
let implicitPrototype = obj?.__proto__;
// 構造函數(shù)的原型
const displayPrototype = constructor.prototype;
// 遍歷原型鏈
while (implicitPrototype) {
// 找到,返回true
if (implicitPrototype === displayPrototype) return true;
implicitPrototype = implicitPrototype.__proto__;
}
// 遍歷結束還沒找到,返回false
return false;
}
myInstanceof函數(shù)接收兩個參數(shù):實例對象obj和構造函數(shù)constructor。
首先拿到實例對象的隱式原型:obj.__proto__,構造函數(shù)的原型對象constructor.prototype。
接著,就可以通過不斷得到上一級的隱式原型:
implicitPrototype = implicitPrototype.__proto__;
來遍歷原型鏈,尋找displayPrototype是否在原型鏈上,若找到,返回true。
當implicitPrototype為null時,結束尋找,沒有找到,返回false。
原型鏈其實就是一個類似鏈表的數(shù)據(jù)結構。
instanceof做的事,就是在鏈表上尋找有沒有目標節(jié)點。從表頭節(jié)點開始,不斷向后遍歷,若找到目標節(jié)點,返回true。遍歷結束還沒找到,返回false。
3. 驗證
寫一個簡單的實例驗證一下自己實現(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正確得出了結果。
有趣的是,usr.__proto__ instanceof Person返回false,說明obj instanceof constructor檢測的原型鏈,不包括obj節(jié)點本身。
JavaScript常見手寫代碼:
到此這篇關于JavaScript 手動實現(xiàn)instanceof的文章就介紹到這了,更多相關JavaScript instanceof內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
微信小程序 騰訊地圖SDK 獲取當前地址實現(xiàn)解析
這篇文章主要介紹了微信小程序 騰訊地圖SDK 獲取當前地址實現(xiàn)解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2019-08-08

