前端高频面试题之instanceof的实现

745 阅读1分钟

instanceof 是什么

instanceof 运算符用于检测构造函数的 prototype 属性是否出现在某个实例对象的原型链上。(来源MDN) 如:

function Car(make, model, year) {
  this.make = make;
  this.model = model;
  this.year = year;
}
const auto = new Car('Honda', 'Accord', 1998);

console.log(auto instanceof Car);
// expected output: true

console.log(auto instanceof Object);
// expected output: true

根据上面定义就可以实现instanceof

我们将实现方法的第一个参数代表实例,第二个参数代表构造函数

function instanceOf () {
  let obj = arguments[0]
  let constructor = [...arguments][1]
  while(obj.__proto__ !== null){
    if(obj.__proto__ === constructor.prototype){
      return true
    }
    obj = obj.__proto__
  }
  return false
}

可以验证一下

function Person () {
  this.name = 'ren'
}
function Animal () {

}
function Woman() {}
Woman.prototype =new Person()
let w1 = new Woman()
console.log(instanceOf(w1,Woman))
console.log(instanceOf(w1,Animal))