## 前端手写代码——instanceof
instanceof
参数:左侧传入的是原型对象,右侧传入的是构造函数或者是Class声明的类(ES6中Class只是语法糖,本质上还是function声明)
作用:instanceof 用于查找左侧变量的原型链上是否有右侧构造函数的原型
// instanceof 判断左边变量的原型链上 是否有右边变量
// instanceof 左边传入的是对象, 右边是构造函数
function my_instanceof(left, right){
// 对于左边参数 如果是非对象直接返回false
if(Object(left) !== left) return false;
// 对于右侧参数可以认为只能是function且必须有prototype属性
if(typeof right !== 'function' || !right.prototype) throw new TypeError('Right-hand side of 'instanceof' is not an object')
let leftValue = left.__proto__;
// let leftValue = Object.getPrototypeOf(right);
let rightValue = right.prototype;
while(leftValue !== null){
if(leftValue === rightValue){
return true;
}
leftValue = Object.getPrototypeOf(leftValue);
}
return false;
}
class Student{
constructor(name){
this.name = name;
}
}
const sss = new Student('123');
console.log(my_instanceof(sss, Student));