JavaScript manual implementation of instanceof method

JavaScript manual implementation of instanceof method

1. Usage of instanceof

instanceof operator is used to detect whether prototype property of the constructor function appears in the prototype chain of an instance object .

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

As shown in the above code, two constructors, Person and Person2 , are defined, and a Person instance object usr is created using the new operation.

Use instanceof operator to check whether prototype property of the constructor is on the prototype chain of the usr instance.

Of course, the results show that prototype properties of Person and Object are on the prototype chain of usr . usr is not an instance of Person2 , so prototype property of Person2 is not on the prototype chain of usr .

2. Implementing instanceof

After understanding the function and principle of instanceof , you can implement a function with the same function as instanceof :

function myInstanceof(obj, constructor) {
    // implicit prototype of obj let implicitPrototype = obj?.__proto__;
    // Constructor prototype const displayPrototype = constructor.prototype;
    // Traverse the prototype chain while (implicitPrototype) {
        // Found, return true
        if (implicitPrototype === displayPrototype) return true;
        implicitPrototype = implicitPrototype.__proto__;
    }
    // The traversal is over and not found yet, return false
    return false;
}

myInstanceof function receives two parameters: the instance object obj and the constructor constructor .

First get the implicit prototype of the instance object: obj.__proto__ , the prototype object of the constructor function constructor.prototype .

Then, you can continue to get the implicit prototype of the previous level:

implicitPrototype = implicitPrototype.__proto__;

To traverse the prototype chain, find out whether displayPrototype is on the prototype chain, and if found, return true .

When implicitPrototype is null , the search ends, and if not found, false is returned.

The prototype chain is actually a data structure similar to a linked list .

What instanceof does is to find out whether there is a target node in the linked list. Starting from the header node, traverse backwards continuously. If the target node is found, return true . If the traversal ends and the object is not found, false is returned.

3. Verification

Write a simple example to verify your implementation of 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

As you can see, myInstanceof produces the correct result.

Interestingly, usr.__proto__ instanceof Person returns false , indicating that the prototype chain detected by obj instanceof constructor does not include obj node itself.

Common handwritten JavaScript codes:

「GitHub — code-js」

This is the end of this article about manually implementing instanceof in JavaScript. For more relevant JavaScript instanceof content, please search 123WORDPRESS.COM’s previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Understanding Javascript_07_Understanding the implementation principle of instanceof
  • Detailed explanation of typeof and instanceof usage in JavaScript
  • Example usage of instanceof operator in JavaScript
  • Example of using instanceof operator in JavaScript
  • JavaScript type detection: defects and optimization of typeof and instanceof
  • Summary of usage of instanceof operator in JavaScript
  • Summary of the difference between typeof and instanceof in JS

<<:  Solution to the problem of not being able to obtain the hostname of the host in the docker container

>>:  Deep understanding of line-height and vertical-align

Recommend

Solution to the problem that elements with negative z-index cannot be clicked

I was working on a pop-up ad recently. Since the d...

js dynamically adds example code for a list of circled numbers

1. Add the ul tag in the body first <!-- Unord...

Div adaptive height automatically fills the remaining height

Scenario 1: Html: <div class="outer"...

Alibaba Cloud Ubuntu 16.04 builds IPSec service

Introduction to IPSec IPSec (Internet Protocol Se...

How to create a web wireframe using Photoshop

This post introduces a set of free Photoshop wire...

Vue implements card flip carousel display

Vue card flip carousel display, while switching d...

Two methods to stretch the background image of a web page

There are two solutions: One is CSS, using backgro...

Tutorial on building an FTP server in Ubuntu 16.04

Ubuntu 16.04 builds FTP server Install ftp Instal...

Some problems you may encounter when installing MySQL

Question 1: When entering net start mysql during ...

Detailed explanation of Nginx timeout configuration

I recently used nginx in a project, and used Java...

MySQL table auto-increment id overflow fault review solution

Problem: The overflow of the auto-increment ID in...