1. Usage of instanceof 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, Use Of course, the results show that 2. Implementing instanceof After understanding the function and principle of 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; }
First get the implicit prototype of the instance object: Then, you can continue to get the implicit prototype of the previous level: implicitPrototype = implicitPrototype.__proto__; To traverse the prototype chain, find out whether When
3. Verification Write a simple example to verify your implementation of 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, Interestingly, 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:
|
>>: Deep understanding of line-height and vertical-align
First, your container must be running You can vie...
1. Link's to attribute (1) Place the routing ...
Here is a single-line layout using ul>li for l...
Mixin method: The browser cannot compile: The old...
Table of contents Cause of the problem: Solution:...
Preface This article mainly introduces 4 methods ...
1. delete delete is the only real way to remove a...
1. Unzip MySQL 5.7 2. Create a new configuration ...
The core is mysqldump and Runtime The operation i...
Table of contents 1. First install echarts in the...
Step 1: Configure environment variables (my decom...
1. Install kvm virtualization : : : : : : : : : :...
1. Compile and install ovs from source code: Inst...
As shown below: XML/HTML CodeCopy content to clip...
1. Command Introduction The read command is a bui...