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

How to configure environment variables in Linux environment

JDK download address: http://www.oracle.com/techn...

How to install Jenkins using Docker

Table of contents 1. Pull the image 2. Create a l...

Introduction to major browsers and their kernels

Trident core: IE, MaxThon, TT, The World, 360, So...

A brief discussion of several browser compatibility issues encountered

background Solving browser compatibility issues i...

Nginx uses reverse proxy to implement load balancing process analysis

Introduction Based on docker container and docker...

HTML form tag tutorial (2):

This tutorial introduces the application of vario...

Introduction to the use of html base tag target=_parent

The <base> tag specifies the default address...

vue3.0+echarts realizes three-dimensional column chart

Preface: Vue3.0 implements echarts three-dimensio...

Vue implements QR code scanning function (with style)

need: Use vue to realize QR code scanning; Plugin...

Six ways to reduce the size of Docker images

Since I started working on Vulhub in 2017, I have...

WeChat applet records user movement trajectory

Table of contents Add Configuration json configur...

Docker FAQ

Docker only maps ports to IPv6 but not to IPv4 St...

The difference and usage of datetime and timestamp in MySQL

1. How to represent the current time in MySQL? In...

MySQL series 6 users and authorization

Table of contents Tutorial Series 1. User Managem...

Summary of methods for writing judgment statements in MySQL

How to write judgment statements in mysql: Method...