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

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

问题描述

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



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



我认为的下一个方法是这样的:

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

return false;
}

这是有效的,但我不能震动我失踪的感觉一些更直接的方法来检查这个。有没有一个?

解决方案

由于 instanceof 应该能够做

  A.prototype instanceof B 
A === B 来测试自我参考:

  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



< hr>

instanceof 基本实现如下:

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

它迭代对象的原型链,检查任何原型是否等于构造函数原型属性。



所以几乎像你在做什么,但内部。


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).

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?

解决方案

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

A.prototype instanceof 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 example:

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 is basically implemented as follows:

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

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天全站免登陆