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

Instanceof works by looking for __proto__ layer by layer, returning true if it is equal to constructive. prototype and false if it never found.

instance.[__proto__...] = = =constructor.prototype
Copy the code

The simulation code is as follows:

function myInstanceof(L, R) {
    let O = R.prototype // take an explicit prototype of R
    L = L.__proto__ // take the implicit prototype of L
    while (true) {
        // Object.prototype.__proto__ === null
        if (L === null) {
            return false
        }
        if (O === L) {
            return true
        }
        L = L.__proto__
    }
}

function Foo(){}
console.log(Foo instanceof Foo) // false
console.log(myInstanceof(Foo,Foo)) // false

console.log(Object instanceof Object) // true
console.log(myInstanceof(Object.Object)) // true

console.log(Function instanceof Function) // true
console.log(myInstanceof(Function.Function)) // true

console.log(Foo instanceof Function) // true
console.log(myInstanceof(Foo,Function)) // true

console.log(Foo instanceof Object) // true
console.log(myInstanceof(Foo,Object)) // true
Copy the code

Reference:

Brief introduction to the realization principle of Instanceof and Typeof

You need to know about prototypes and prototype chains

Diagram prototype chains and their inheritance advantages and disadvantages

Implement instanceof.md manually