I need to implement two functions in JavaScript: isConstructor(x) and constructorName(x)
isConstructor(x) should return true in case the argument x is a constructor function, and false, otherwise. For example,
isConstructor(Date) === true
isConstructor(Math.cos) === false
constructorName(x) should return the constructor name for each proper constructor function x. So e.g.
constructorName(Date) === 'Date'
I can only think of an ugly implementation for both functions, where I create a command string
"var y = new x()"
which is then called with an eval(command) in a try/catch statement. If that eval call succeeds at all, I call x a constructor. And I retrieve the name of x indirectly by asking for the class name of the prototype of y, something like
var constrName = Object.prototype.toString.call(y).slice(8,-1); // extracts the `ConstrName` from `[object ConstrName]`
return constrName;
But all this is very ugly, of course. How can I do this properly?
[[Call]]method, so can be called. Objects created by calls to constructors are Objects (which don't have[[Call]]), not Functions.