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
instanceof
function 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