手寫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的原型鏈上
}
}