Skip to content

实现instanceOf

js
function myInstanceOf(a, b) {
  let left = a.__proto__
  let right = b.prototype
  while (true) {
    if (left == null) {
      return false
    }
    if (left == right) {
      return true
    }
    left = left.__proto__
  }
}
js
function myInstanceOf2(left, right) {
  let proto = Object.getPrototypeOf(left)
  prototype = right.prototype
  while (true) {
    if (!proto) return false
    if (proto === prototype) return true
    proto = Object.getPrototypeOf(proto)
  }
}
js
function myInstanceof(left, right) {
  while (true) {
    if (left === null) {
      return false
    }
    if (left.__proto__ === right.prototype) {
      return true
    }
    left = left.__proto__
  }
}
js
function my_instanceof(a, b) {
  while (a) {
    if (a.__proto__ === b.prototype) return true
    a = a.__proto__
  }
  return false
}

如有转载或 CV 的请标注本站原文地址