手写instanceof
我们通过instanceof检测一个实例不是某一个类时,如果这个实例是这个类的实例那么就会返回true,否则就会返回false
原理
function grandpa(){
}
function father(){
}
father.prototype = new grandpa()
function son(){
}
son.prototype = new father()
let xiaoming = new son()
console.log(xiaoming instanceof son);//true
console.log(xiaoming instanceof father);//true
console.log(xiaoming instanceof grandpa);//true
原因:
xiaoming.__proto__ == son.prototype,//true
xiaoming.__proto__.__proto__ == father.prototype,//true
xiaoming.__proto__.__proto__.__proto__ == grandpa.prototype//true
这也是instanceof查找的机制
手写instanceof
function _instanceof(obj,constructor){
if (obj == null || !/^(object|function)$/.test(typeof obj)){
return false;
//如果没有传入obj,或者是传入的不是一个引用类型的值,那么直接返回false
}
if (typeof constructor !=='function'){
//如果constructor不是一个函数,那么也是直接返回false
}
let objproto = obj.__proto__
let protoype = constructor.prototype
while(true){
if (objproto == protoype){
return true;
}else {
objproto = objproto.__proto__
}
if (objproto == null){
//如果找到Object.prototype.__proto__,那么就直接返回false
return false;
}
}
}
--------------------------------------
//验证:
function grandpa(){
}
function father(){
}
father.prototype = new grandpa()
function son(){
}
son.prototype = new father()
let xiaoming = new son()
console.log(_instanceof(xiaoming,son));//true
console.log(_instanceof(xiaoming,father));//true
console.log(_instanceof(xiaoming,grandpa));//true