JavaScript-手写 instanceof 方法
手写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的原型链上
}
}

浙公网安备 33010602011771号