If you have an instance of an object in javascript, it seems it that can be difficult to find its actual type, ie
var Point2D = function Point2D(x, y) {
return {
X: x,
Y: y
}
}
var p = new Point2D(1,1);
typeof p // yields just 'Object' not 'Point2D'
One way around it I found was to make the object its own prototype, and then you can gets its name effectively by calling prototype.constructor.name,
var Point2D = function Point2D(x, y) {
return {
X: x,
Y: y,
prototype: this
}
}
new Point2D(1,1).prototype.constructor.name // yields 'Point2D'
Would this be an OK way of doing it (what are the pros/cons?) or is there a better practice I am missing out on?
Thanks.
First we need to fix how you are building your class, since you are tripping in some JS pitfalls and doing some really weird stuff:
Now we can tackle the part about getting the type names. The better practice you are missing on is not inspecting the type in the first place. From an OO perspective it shouldn’t matter how an object is implemented (ts class) but how it behaves and what is its interface (exposed methods and properties). Also, from a Javascript perspective, type names are a second-class hack that don’t fit very well with the prototypical OO scheme that is actually used.
Since there are many reasons you could be trying to inspect a type name in the first place, there are many different “best” solutions. Some that I could think of:
If all you case about is “does this object implement a particular point interface” then you can do feature-inspection directly:
If you use the type names to do dispatching consider using a method instead. Its the natural OO way.
becomes
If you really need some sort of tag, you can explicitely make one, as pointed by some of the other answers already:
The advantages here are that you can have more than one class have the same “type” if you need to and that you don’t have to worry about any of the tricky
instanceofortypeofcorner cases.