检查一个类是否是另一个类的超类
我有一组类(不是对象)。仅当没有子类不存在时,我才需要向数组添加新类。但是这段代码不起作用,因为这些不是启动的对象。
import {A} from './a';
import {B} from './b';
import {otherList} from './list';
export const getList =()=>{
const list = [A,B];
otherList.forEach((element) => {
if (list.findIndex((item) => element instanceof item) === -1) {
list.push(element);
}
});
return list;
}
回答
JavaScript 继承通过从超类构造函数创建原型来工作。
这意味着如果你有这样的事情:
class A { }
class B extends A { }
class C extends B { }
然后您可以使用以下命令检查子类.prototype:
console.log(A.prototype instanceof Object);
console.log(B.prototype instanceof Object);
console.log(B.prototype instanceof A);
console.log(C.prototype instanceof A);
console.log(C.prototype instanceof B);
console.log(C.prototype instanceof C); // false
true除了最后一个,这些都记录了。
基于此,您可以构建此函数来检查一个类是子类还是与另一个类相同:
declare type Class = new (...args: any[]) => any;
function isSubClassOf(cls: Class, superCls: Class): boolean {
return cls === superCls || cls.prototype instanceof superCls;
}
这些都记录true除了最后一个:
console.log(isSubClassOf(C, A));
console.log(isSubClassOf(C, B));
console.log(isSubClassOf(C, C));
console.log(isSubClassOf(B, A));
console.log(isSubClassOf(A, A));
console.log(isSubClassOf(A, C)); // false
在你的情况下,你可以使用这样的函数:
if (list.findIndex((item) => isSubClassOf(element, item)) === -1) {
list.push(element);
}