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 obtain root permissions in a docker container

First, your container must be running You can vie...

React Routing Link Configuration Details

1. Link's to attribute (1) Place the routing ...

Examples of 4 methods for inserting large amounts of data in MySQL

Preface This article mainly introduces 4 methods ...

How to delete a property of an object in JavaScript

1. delete delete is the only real way to remove a...

Detailed installation and configuration tutorial of MySQL 5.7 under Win10

1. Unzip MySQL 5.7 2. Create a new configuration ...

MySQL backup table operation based on Java

The core is mysqldump and Runtime The operation i...

Vue+Echart bar chart realizes epidemic data statistics

Table of contents 1. First install echarts in the...

Detailed explanation of basic management of KVM virtualization in CentOS7

1. Install kvm virtualization : : : : : : : : : :...

How to install and uninstall open-vswitch in Linux

1. Compile and install ovs from source code: Inst...

HTML page common style (recommended)

As shown below: XML/HTML CodeCopy content to clip...

Use of Linux read command

1. Command Introduction The read command is a bui...