Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JavaScript 实现 instanceof 运算符 #12

Open
ChuChencheng opened this issue Dec 30, 2019 · 0 comments
Open

JavaScript 实现 instanceof 运算符 #12

ChuChencheng opened this issue Dec 30, 2019 · 0 comments

Comments

@ChuChencheng
Copy link
Owner

ChuChencheng commented Dec 30, 2019

定义

检测构造函数的 prototype 属性是否出现在某个实例对象的原型链上。

实现

  1. 先判断构造函数是否合法
  2. 在实例的原型链上查找是否有等于 F.prototype 的原型
function _instanceof (instance, constructor) {
  if (typeof constructor !== 'function') {
    throw new TypeError(`Right-hand side of 'instanceof' is not callable`)
  }
  const isPrimitive = (value) => value == null || (typeof value !== 'object' && typeof value !== 'function')
  const constructorPrototype = constructor.prototype
  let prototype = instance
  while (!isPrimitive(prototype)) {
    prototype = Object.getPrototypeOf(prototype)
    if (prototype === constructorPrototype) return true
  }
  return false
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant