Design ES6: appropriate way to identify group of classes

96 Views Asked by At

I have a group of classes, they share no properties. What i want to do is to check if arbitrary object is instance of any class in this group. I could think of two approaches, first is to define a special signature property in every one of those classes like string for example and check for it in the arbitrary object, second approach is to inherit all classes from an empty class and check if this arbitrary object is instanceof the base class constructor, so is it ok to inherit from an empty class ? and Which one is more appropriate ? or there's a better approach ?

2

There are 2 best solutions below

3
On

I would say you should go with inheritance here, as it semantically and intuitively makes the most sense. You have a group of classes, and they belong to a common set, and even if they don't share concrete properties with that parent, they do share the abstract property that they 'belong' to that parent.

Multiple approaches work of course, but I think this is the one that represents the idea best.

6
On

Well I don't use classes but it should be the same with constructor functions since JS classes are just syntactical sugar. So,

function Maker(n){
  this.number = n;
}

Maker.prototype.getConstructorName = function(){
                                       return this.constructor.name;
                                     };

var obj1 = new Maker(10);
console.log(obj1.getConstructorName());