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
I was working on a pop-up ad recently. Since the d...
1. Add the ul tag in the body first <!-- Unord...
Scenario 1: Html: <div class="outer"...
Introduction to IPSec IPSec (Internet Protocol Se...
This post introduces a set of free Photoshop wire...
Vue card flip carousel display, while switching d...
There are two solutions: One is CSS, using backgro...
Experimental environment: 1. Three CentOS 7 serve...
The general way of writing is as follows: XML/HTM...
This article shares with you the graphic tutorial...
Ubuntu 16.04 builds FTP server Install ftp Instal...
Mixin method: The browser cannot compile: The old...
Question 1: When entering net start mysql during ...
I recently used nginx in a project, and used Java...
Problem: The overflow of the auto-increment ID in...