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

模拟实现instanceof并谈其原理 #5

Open
impeiran opened this issue Apr 14, 2020 · 0 comments
Open

模拟实现instanceof并谈其原理 #5

impeiran opened this issue Apr 14, 2020 · 0 comments

Comments

@impeiran
Copy link
Owner

instanceof用来判断左侧变量是否为右边变量的实例,而创造一个实例的new关键字,其实就是根据构造函数的原型属性prototype创造新的对象,并以其为上下文执行构造函数。

因此,对于实现instanceof,我们可以获取左侧变量的构造函数的原型对象,跟右侧变量的原型对象进行比较。

但这样只是获取原型链上目标对象的直接父级,还需要逐层递归往原型链上面进行查找。

JS的对象里就有一个属性__proto__,指向的就是当前对象的构造函数的原型,我们可以基于此实现instanceof

/**
 * mock instanceof
 * @param {Any} left 
 * @param {Any} right 
 */
const _instanceof = (left, right) => {
  if (!left || !right) return new Error('lack of parameter')

  let proto = left.__proto__

  right = right.prototype || {}

  while (proto) {
    if (proto === right) {
      return true
    } else {
      proto = proto.__proto__
    }
  }

  return false
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant