In ES6 there is .constructor.name
which can be used on any object to get its class name.
Is there something in ES5 that can do that?
(Note: Before commenters mention to upgrade the browser, etc., this question is about development for Fitbit, which uses JerryScript, a lightweight ES5.1-based engine)
TLDR of code that does not work:
class something {
constructor() {
console.log(this.constructor.name);
}
}
new something();
It should normally output something
, I guess, but it just says undefined
.
Section 13.2 of the ECMAScript 5.1 specification explains how all functions have a
prototype
property which itself has aconstructor
property.So any object created with
new someFunction
should, by default, inherit theconstructor
property whose value is thesomeFunction
function. The specification also specifies theconstructor
property of builtin object prototypes.However, it does not mention the existence of a
name
property on constructors or functions. So if you want to specifically get the name of the constructor as a string, you would have to extract it from the representation returned by.toString()
which is defined as such:Alternatively, you can use
Object.prototype.toString.call(obj)
to produce a string which exposes the internal [[Class]] of a value, which is slightly different notion than the constructor property. Again, you'll have to extract the [[Class]] from the string yourself. Sadly, for custom functions, that just returns[object Object]
, so probably not what you're looking for.