溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

JavaScript如何手動實現(xiàn)instanceof

發(fā)布時間:2021-10-29 13:05:13 來源:億速云 閱讀:134 作者:小新 欄目:開發(fā)技術(shù)

這篇文章將為大家詳細講解有關JavaScript如何手動實現(xiàn)instanceof,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。

1. 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ù),PersonPerson2,又實用new操作創(chuàng)建了一個Person的實例對象usr。

實用instanceof操作符,分別檢驗構(gòu)造函數(shù)prototype屬性是否在usr這個實例的原型鏈上。

當然,結(jié)果顯示,PersonObjectprototype屬性在usr的原型鏈上。usr不是Person2的實例,故Person2prototype屬性不在usr的原型鏈上。

2. 實現(xiàn)instanceof

明白了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。

implicitPrototypenull時,結(jié)束尋找,沒有找到,返回false。

原型鏈其實就是一個類似鏈表的數(shù)據(jù)結(jié)構(gòu)。

instanceof做的事,就是在鏈表上尋找有沒有目標節(jié)點。從表頭節(jié)點開始,不斷向后遍歷,若找到目標節(jié)點,返回true。遍歷結(jié)束還沒找到,返回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正確得出了結(jié)果。

關于“JavaScript如何手動實現(xiàn)instanceof”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,使各位可以學到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI