【问题标题】:Check if a class is a super-class of another class检查一个类是否是另一个类的超类
【发布时间】:2021-08-07 20:44:10
【问题描述】:

我有一个类数组(不是对象)。只有当没有子类不存在时,我才需要向数组中添加新类。但是这段代码不起作用,因为这些不是启动的对象。


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 arrays typescript


    【解决方案1】:

    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);
    }
    

    【讨论】:

      猜你喜欢
      • 2010-10-21
      • 2011-06-02
      • 2013-04-09
      • 2018-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多