简体   繁体   English

JavaScript继承-如何检查类类型?

[英]Javascript inheritance - how to check class type?

I have implemented inheritance in javascript like this: Parent class: 我已经在javascript中实现了继承,如下所示:父类:

class Parent {
  constructor(data) {
    super(data);
    ...
  }
}
export default Parent;

and children classes: ChildA 和儿童班:ChildA

class ChildA extends Parent {
  constructor(data) {
    super(data);
    ...
  }
}

export default ChildA;

and ChildB: 和ChildB:

class ChildB extends Parent {
  constructor(data) {
    super(data);
    ...
  }
}

export default ChildB;

Now I got from server object which is mapped to one of these children base on flag. 现在,我从服务器对象获得了一个对象,该对象根据标志映射到这些子对象之一。 This flag is not in objects, so is possible how to later in code what of type is my object? 该标志不在对象中,因此如何在以后的代码中实现对象的类型是什么?

I tried myObj.constructor.name == 'ChildA' and myObj.constructor.name == 'ChildB' but it always returns false. 我尝试了myObj.constructor.name == 'ChildA'myObj.constructor.name == 'ChildB'但它始终返回false。

The simplest solution would be to have a type property on your classes that tells what kind of class each one is. 最简单的解决方案是在您的类上具有type属性,以告知每个类是哪种类。 It makes checking very simple. 它使检查非常简单。

A more involved solution would be to use Typescript , which has inheritance and typeguards built in. 一个更复杂的解决方案是使用Typescript ,它内置了继承和Typeguards。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM