Getting the class name from an object instance

I was recently assigned to work on a node.js project — a first, for me. I discovered that it comes with a neat CLI debugger built in, which is very handy when diving into an unknown codebase. However, when inspecting a variable, it doesn’t show me its type; only its value.

First, let’s see how you would get the type of an object in other dynamic languages.

In Ruby, every object responds to a class message, which returns an object of type Class, which responds to a name message, which returns a string:

obj.class.name

In Python, every object has a __class__ property, which contains a type instance, which has a __name__ property, which contains a string:

obj.__class__.__name__

In PHP, there’s a special get_class() function which returns the class name of an object as a string:

get_class($obj);

In JavaScript, every object has a constructor property, which contains a Function object, which has a name property, which contains a string:

obj.constructor.name

Update: Got a link on twitter to a much more in-depth discussion on StackOverflow, with various caveats and workarounds. But for getting a general idea of what kind of object a variable is, I think the above method is good enough.

comments powered by Disqus