面试时被问到了,虽然思路说了出来,但写的时候还是磕磕巴巴的,让面试官提醒了才写出来,太丢人了┭┮﹏┭┮

思路

instanceof 运算符用于判断构造函数的 prototype 属性是否出现在对象的原型链中的任何位置。

实现步骤:

  1. 获得对象的原型
  2. 获得构造函数的prototype
  3. 循环判断对象的原型是否等于构造函数的prototype,如果不等于,则根据原型链往下找,直到对象原型为null
  1. function _instanceof(left, right) {
  2. let letfProto = left.__proto__
  3. let rightPrototype = right.prototype
  4. // 当letfProto不为null时,则一直循环遍历直到找到构造函数的 prototype属性
  5. while (letfProto) {
  6. if (letfProto === rightPrototype) {
  7. return true
  8. }
  9. letfProto = letfProto.__proto__
  10. }
  11. return false
  12. }
  13. console.log(_instanceof([], Array)); // true
  14. console.log(_instanceof([], Object)); // true
  15. console.log([] instanceof Array); // true
  16. console.log([] instanceof Object); // true