面试题 - 手写 instanceof

instanceof 的作用

instanceof 运算符返回一个布尔值,表示对象是否为某个构造函数的实例(包括继承而来)。
instanceof 运算符用于检测: 某个实例对象的原型链上,是否有出现某个构造函数的 prototype 属性。

换句话说就是,顺着实例对象的隐式原型一层层往上找,看能否找到某个构造函数的显式原型。如果能,返回 true,否则返回 false

例如:

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

手写 myInstanceOf 函数

function myInstanceOf(obj, clas) {
  let pointer = obj
  while(pointer) {
    if(pointer === clas.prototype) {
      return true
    }
    pointer = pointer.__proto__
  }
  return false
}
posted @ 2022-04-11 13:59  Better-HTQ  阅读(38)  评论(0编辑  收藏  举报