Home > Blockchain >  How to change Javascript function name that appears in toString()?
How to change Javascript function name that appears in toString()?

Time:10-09

Function.name property is configurable and can be overriden, but if I try

function foo() {}
Object.defineProperty(foo, 'name', {value: 'bar'})

foo.toString() still shows up as "function foo() {}" but I expected it to be "function bar() {}".

CodePudding user response:

You can't do this 100% reliably. That's because of the definition of Function.prototype.toString, which uses the [[SourceText]] internal slot, which is set as the function is being created from the source code that was used to create the function. It doesn't use the name property.

You could try to override toString on the function as well, but of course that would still fail if someone explicitly used Function.prototype.toString on it.

  • Related