current position:Home>Understanding instanceof from principle

Understanding instanceof from principle

2021-08-27 08:34:18 Always_ positive

This is my participation 8 The fourth of the yuegengwen challenge 23 God , Check out the activity details :8 Yuegengwen challenge

With typeof Why do we still need instanceof?

We all know typeof It can help us judge the data type , But in judgment object When it comes to type typeof Can only tell us that object But it can't tell us what kind of object, Look at the code below .instanceof The emergence of can solve this problem .


instanceof Implementation principle of

Introducing instanceof Before the concrete usage of , Let's take a look first instanceof Implementation principle of , Starting from the principle can better help us understand its usage . In order to make readers better understand the code , We need until the following preparatory knowledge .

  • Object.prototype.__proto__ === null
  • Object.prototype Is an empty object

Realization instanceof The three-step strategy of , Please distinguish what is a prototype and what is a prototype object ,proto Refers to the prototype ,prototype It refers to the prototype object .

First step : Get the prototype of the expression on the left

let leftProto = leftVaule.__proto__;
 Copy code 

The second step : Get the prototype object of the expression on the right

let rightProtoType = rightVaule.prototype;
 Copy code 

The third step : Loop to determine whether there is an expression on the right on the prototype chain of the expression on the left

while (true) {
    if (leftProto === null) {
        return false;
    if (leftProto === rightProtoType) {
        return true;
    //  Continue looking up the prototype chain of the expression on the left 
    leftProto = leftProto.__proto__
 Copy code 

Realization instanceof


A few help understand instanceof Example

function test() {}
console.log(test.__proto__ === Function.prototype); //true
Object instanceof Object // true
Function instanceof Function // true
Function instanceof Object // true
test instanceof test // false
test instanceof Object // true
test instanceof Function // true
 Copy code 

To accurately understand the above example , We have to talk to what we said above instanceof Principle , The trick is to get the prototype of the left expression and the prototype object of the right expression , Judge whether the prototype object of the right expression is on the prototype chain of the left expression .

Reference material

Talking about instanceof and typeof Implementation principle of

copyright notice
author[Always_ positive],Please bring the original link to reprint, thank you.

Random recommended