so 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();
should normally output something
, I guess but just says undefined
2
Answers
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.ES5.1 function objects did not have a
.name
property. This was a widely-supported but non-standard extension that only got added to the spec with ES6.CoreJs has a polyfill for it which relies on
Function.prototype.toString()
, which is supported in the latest JerryScript but may have to be enabled with theJERRY_FUNCTION_TO_STRING
build option.