The instanceof operator is used to check whether the constructor’s prototype property appears on the prototype chain of an instance object.

In plain English, it means to determine whether an instance belongs to a type or to its parent or ancestor class.

Function Parent() {this.nums = 100} function Child (chi) {this.chi = chi} Child. Prototype = new Parent( const ming = new Child('tennis') ming instanceof Child // true ming instanceof Parent // trueCopy the code

Child inherits Parent through archetypal chain inheritance, so Ming is of both Child and Parent type. Now that you know how to use instanceof, let’s implement it.

To determine whether A belongs totype B, we only need when B exists on the prototype chain of A, that is, A searches up along __proto__. Once B’s prototype object b. prototype can be accessed, it indicates that A belongs totype B, otherwise A will eventually point to null along __proto__.

While loop, right now, it’s you.

function new_instanceof(left, right) { let _left = left.__proto__ while (_left ! == null) { if (_left === right.prototype) { return true } _left = _left.__proto__ } return false }Copy the code

That’s the main principle behind Instanceof, well, it’s just a few lines, it’s super simple, and it connects a wave of prototypes, a chain of prototypes, doesn’t it smell good…

Hand tear JS prototype, prototype chain

Hand rip JS inheritance