The instanceof operator is used to check whether the prototype property of a constructor appears on the prototype chain of an instance object, such as Object instanceof constructor, Check whether constructor. Prototype exists on the prototype chain of the parameter Object.
Oh, that’s so easy
function myinstanceof(a,b){
return a instanceof b
}
Copy the code
Jimei don’t hit me, this is my intention, dare again.
Object. GetPrototypeOf (a) : Object. GetPrototypeOf (a) : Object.
let arr = [];
console.log(Object.getPrototypeOf(arr) === arr.__proto__) //true
Copy the code
The following code is implemented through a prototype chain lookup, and the second argument must be a constructor.
function myinstanceof(a, b) {
let prototypeA = Object.getPrototypeOf(a),
prototypeB = b.prototype;
while (prototypeA) {
if (prototypeA === prototypeB) return true;
prototypeA = Object.getPrototypeOf(prototypeA);
}
return false
}
let arr = [];
let obj = {};
console.log(myinstanceof(Array.Object)) // true
console.log(myinstanceof(arr, Object)) // true
console.log(myinstanceof(arr, obj)) // false
console.log(myinstanceof(obj, arr)) // false
Copy the code
Nothing, just get the prototype, look up the prototype chain, compare their two prototypes are equal, until null.
The more convoluted code is the following, and handles the passing of non-constructors, so you can see that the prototype chain is already solid.
function myinstanceof(a,b){
let prototypeA = typeof a == 'function' ? a.prototype : a
let prototypeB = typeof b == 'function' ? b.prototype : b
while(prototypeA ! =null) {if(prototypeA.constructor.name === prototypeB.constructor.name) return true
prototypeA = prototypeA.__proto__;
}
return false
}
let arr = [];
let obj = {};
console.log(myinstanceof(Array.Object)) // true
console.log(myinstanceof(arr, Object)) // true
console.log(myinstanceof(arr, obj)) // true
console.log(myinstanceof(obj, arr)) // false
Copy the code
As you can see, the second argument passed to a non-constructor is recognized because the code above converts the passed non-constructor to a function, and then checks to see if B (or its constructor) exists in a’s prototype chain, even if the order is reversed.