在Javascript toString中获取价值

Nit*_*esh 3 javascript prototype object

我有一个非常简单的问题.

在Javascript中,

"你好"+ function(){}

将打印 "hellofunction(){}"

因为Function.prototype将调用自己的toString方法,它将返回"function(){}"

现在,我想重写toString方法:

Function.prototype.toString = function(){
return "my" + SOME_PROPERTY + "output"
}
Run Code Online (Sandbox Code Playgroud)

在这个自定义方法中,我想function(){} 知道如何在toString方法中获取当前值,因为我无法toString再次执行,因为它将进行递归.

我希望最终输出为:

"myfunction(){}output"
Run Code Online (Sandbox Code Playgroud)

Cer*_*nce 6

通过保存对原始 Function.prototype.toString函数的引用,您可以.call稍后在自定义内部toString,为您提供所需的输出并避免递归:

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