Since ES5 doesn't support Function#name
. I was looking for a way to emulate that functionality. While a lot of people recommend using Function#toString
, others strongly advised against it.
So what are the risks of using the below code to get the name of a function?
if (!Object.hasOwnProperty(Function.prototype, "name")) {
Object.defineProperty(Function.prototype, "name", {
configurable: false,
enumerable: true,
get: function() {
var result = /function\s+([^\s(]+)/.exec(this.toString());
return result ? result[1] : "";
}
});
}
Since ES5 doesn't support arrow functions, I don't really see when the where the risk lies.
As the ECMAScript 5.1 specification says, the
toString
method returns a string that has the syntax of FunctionDeclaration:FunctionDeclaration has the following syntax:
And Identifier defined like:
Conclusion
Although it isn't a beautiful way to get the function name (but the only way in ES5), if you make it parse all of the possibilities listed above, it can work safely in ES5.
But the ES6 standard modified the specifications for
.toString()
, which implies more possible syntaxes, making it unsafe to use this method in it.So, use this method only in versions prior to ES6.