【JavaScript】手写实现 instanceof

153 阅读1分钟
obj instanceof ConstructorFn

instanceof的作用:判断 ConstructorFn.prototype 是否在obj的原型链上

function myInstandeOf(obj, constructor) {
  if (obj !== null && (typeof obj === 'object' ||  typeof obj === 'function')) {
    let p = obj.__proto__
    while(p) {
      if (p === constructor.prototype) return true
      p = Object.getPropertyOf(p)
    }
    return false
  }
  return false
}

myInstandeOf(myInstandeOf, Function) // true
myInstandeOf(myInstandeOf, Object) // true
myInstandeOf({}, Object) // true
myInstandeOf([], Array) // true