instanceof:用来判断右边构造函数的原型对象,是否在左边实例对象的原型链上。
class Person {
}
class Student extends Person {
}
let p1 = new Person()
let stu1 = new Student()
console.log(p1 instanceof Person) //true
console.log(stu1 instanceof Student) //true
console.log(stu1 instanceof Person) //true
用js来实现instanceof,并取名为MyIntanceOf
function MyInstanceOf(left, right) {
let proto = Object.getPrototypeOf(left) //获取左边对象的原型
let prototype = right.prototype //获取右边构造函数的原型对象
while(true) {
if(!proto) return false
if(proto === prototype) {
return true
}
proto = Object.getPrototypeOf(proto)
}
}
class Person {
}
class Student extends Person{
}
let p1 = new Person()
let stu1 = new Student()
console.log(p1 instanceof Person) //true
console.log(MyInstanceOf(p1, Person)) //true
console.log(stu1 instanceof Person) //true
console.log(MyInstanceOf(stu1, Person)) //true
console.log(stu1 instanceof Student) //true
console.log(MyInstanceOf(stu1, Student)) //true
console.log(p1 instanceof Student) //false
console.log(MyInstanceOf(p1, Student)) //false