instanceof方法instanceof判断数据类型的原理通过原型链来实现继承关系的判断(判断变量的__proto__属性和构造函数的prototype属性的指向是否相同)
例1:判断num是否属于Number类型
var num = new Number(1);
console.log(num instanceof Number); // true

可以看到num的__proto__和Number的prototype指向相同,所以instanceof返回为true。
例2:自定义函数继承,利用instanceof判断继承关系
function Animal(name, calls) {
this.name = name;
this.say = function() {
console.log(calls);
}
}
const Cat = new Animal(‘猫‘, ‘喵‘);
const Dog = new Animal(‘狗‘, ‘汪‘);

Cat.__proto__指向Animal,故Cat instanceof Animal返回true

instanceoffunction myInstanceof(left, right) {
let proto = left.__proto__;
let prototype = right.prototype;
// proto为空,即遍历到原型链的尽头
// prototype为空,传入的构造函数异常
if (proto === null || prototype === null) {
return false;
} else if(proto === prototype){
return true;
} else {
myInstanceof(proto, right); // 遍历,判断right是否left的原型链上
}
}
原文:https://www.cnblogs.com/chenjy259/p/14829268.html