Getting value inside Javascript toString

Viewed 53

I have a very simple question.

In Javascript,

"hello" + function(){}

will print "hellofunction(){}"

because Function.prototype will call its own toString method and it will return "function(){}"

Now, I want to override toString method as:

Function.prototype.toString = function(){
return "my" + SOME_PROPERTY + "output"
}

Inside this custom method, I want to get function(){} I want to know how to get this current value inside toString method since I can't execute toString again as it will go in recursion.

I want final output as:

"myfunction(){}output"
1 Answers

By saving a reference to the original Function.prototype.toString function, you can .call it later, inside your custom toString, giving you the output you want and avoiding recursion:

const origToString = Function.prototype.toString;
Function.prototype.toString = function(){
  return "my" + origToString.call(this) + "output"
}
console.log("" + function(){});

Related