检查一个构造函数是否在ES6中继承另一个 [英] Check if a constructor inherits another in ES6
问题描述
最快的方式可能是(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
$ p $但是这只会测试继承,你应该比较
A === B
来测试自我参考:A === B || A.prototype instanceof B
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 doA.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
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屋!