I thought there are 5 primitive types for JavaScript (null, undefined, boolean, number, string), and then there is object (which includes array, function, and custom defined pseudo class objects). But it is somewhat strange that
typeof null
is "object", and there is no easy way to get back the object class name for pseudo-classical class such as Person, Author. I wonder if there is a newer operator or function that can return possibly lower case names for primitive type (and "null" for null, not "object"), and capital case for custom-defined pseudo-classical objects?
If no such operator or function exist in ECMA-5 or later, would it make sense to have it? Otherwise, we may need to rely on our own definition or any framework, but that will not be standard across different platforms.
ECMAScript 5 objects have an internal property known as
[[Class]]. This is the closest thing in ES5 to what you’re asking. You can access[[Class]]withObject.prototype.toStringas follows:This behavior is crucial for adequately identifying objects which come from other frames.
However, it doesn’t work for user-defined constructors. Objects created with user-defined constructors have
[[Class]]"Object".It looks like ECMAScript 6 might have the ability to extend what’s returned by
Object.prototype.toString, so thatgetClassOf(foo)could be"Foo"through the@@toStringTagsymbol.See https://mail.mozilla.org/pipermail/es-discuss/2012-September/025344.html for more information on the upcoming standard.
You could create your own function to do what you want like this:
Examples: