检查一个构造函数是否继承了 ES6 中的另一个 [英] Check if a constructor inherits another in ES6

查看:18
本文介绍了检查一个构造函数是否继承了 ES6 中的另一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一种情况,我需要检查一个构造函数 (X) 在其原型链中是否有另一个构造函数 (Y)(或者是 Y 本身).

I have a situation where I need to check if a constructor (X) has another constructor (Y) in its prototype chain (or is Y itself).

最快的方法可能是(new X()) instanceof Y.在这种情况下,这不是一个选项,因为如果在没有有效参数的情况下实例化,则有问题的构造函数可能会抛出异常.

The quickest means to do this might be (new X()) instanceof Y. That isn't an option in this case because the constructors in question may throw if instantiated without valid arguments.

我考虑的下一个方法是:

The next approach I've considered is this:

const doesInherit = (A, B) => {
  while (A) {
    if (A === B) return true;
    A = Object.getPrototypeOf(A);
  }

  return false;
}

那行得通,但我无法动摇我缺少一些更直接的方法来检查这个的感觉.有吗?

That works, but I can't shake the sense that I'm missing some more straightforward way to check this. Is there one?

推荐答案

由于instanceof的工作方式,你应该可以做到

Because of the way instanceof works, you should be able to do

A.prototype instanceof B

但这只会测试继承,你应该比较A === B来测试自引用:

But this would only test inheritance, you should have to compare A === B to test for self-reference:

A === B || A.prototype instanceof B

Babel 示例:

class A {}
class B extends A {}
class C extends B {}

console.log(C === C) // true
console.log(C.prototype instanceof B) // true
console.log(C.prototype instanceof A) // true

<小时>

instanceof 基本实现如下:

function instanceof(obj, Constr) {
  var proto;
  while ((proto = Object.getProtoypeOf(obj)) {
    if (proto === Constr.prototype) {
      return true;
    }
  }
  return false;
}

它遍历对象的原型链并检查是否有任何原型等于构造函数的prototype属性.

It iterates over the prototype chain of the object and checks whether any of the prototypes equals the constructors prototype property.

几乎就像你在做的那样,但在内部.

So almost like what you were doing, but internally.

这篇关于检查一个构造函数是否继承了 ES6 中的另一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆