I want to be able to check if a function is of a given class type in javascript. For example, let's say I have two classes:
class Horse {}
class Chicken {}
And let's say I want to create a function that will tell me if a function passed is Horse, something like that:
function isHorseClass(func) {
// check if func is of Horse class type
return isHorse;
}
The function will be called in the following way:
isHorseClass(Horse) // should return true
isHorseClass(Chicken) // should return false
Notice that the class is passed dynamically without instantiating the object of a class, so I cannot use instanceof
to check the type here. Is there a way to check the type of the class dynamically, like in the example above?
For an exact match, you can just use
===
:...but if you want to also get
true
forHorse
subclasses, then that's possible withclass
syntax (not as much with the older ES5 syntax, but keep reading). You can do this:That works because
class
syntax sets up two inheritance lines: one for the prototype assigned to instances, and a different one for the constructor functions themselves. For instance:That creates these two chains:
This is fairly unique to JavaScript. :-)
Live Example:
With ES5, though (including standard versions of how
class
syntax is transpiled to ES5), you can't do that because they usually don't set up the constructor function inheritance (because you couldn't without ES2015+ featuers). You can get close by checking just the prototype chain, though. Combining that with the earlier version:That will produce false positives. For instance, if I did this:
...it would produce a false positive for
Unrelated
.