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
JDK download address: http://www.oracle.com/techn...
Table of contents 1. Pull the image 2. Create a l...
Trident core: IE, MaxThon, TT, The World, 360, So...
background Solving browser compatibility issues i...
Introduction Based on docker container and docker...
This tutorial introduces the application of vario...
The <base> tag specifies the default address...
Preface: Vue3.0 implements echarts three-dimensio...
need: Use vue to realize QR code scanning; Plugin...
Since I started working on Vulhub in 2017, I have...
Table of contents Add Configuration json configur...
Docker only maps ports to IPv6 but not to IPv4 St...
1. How to represent the current time in MySQL? In...
Table of contents Tutorial Series 1. User Managem...
How to write judgment statements in mysql: Method...