程序员社区

js中instanceof的作用,并实现instanceof

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

赞(0) 打赏
未经允许不得转载:IDEA激活码 » js中instanceof的作用,并实现instanceof

一个分享Java & Python知识的社区