我有一个非常简单的问题。
在 JavaScript 中,
“你好”+ function(){}
将打印 “hellofunction(){}”
因为 Function.prototype 会调用它自己的 toString
方法,它会返回 "function(){}"
现在,我想将 toString 方法重写为:
Function.prototype.toString = function(){
return "my" + SOME_PROPERTY + "output"
}
在这个自定义方法中,我想获取 function(){}
我想知道如何在 toString 方法中获取当前值,因为我无法再次执行 toString
,因为它将递归。
我希望最终输出为:
"myfunction(){}output"
最佳答案
通过保存对原始Function.prototype.toString
函数的引用,您可以稍后在自定义中
,为您提供所需的输出并避免递归:.call
它>toString
const origToString = Function.prototype.toString;
Function.prototype.toString = function(){
return "my" + origToString.call(this) + "output"
}
console.log("" + function(){});
关于javascript - 在 Javascript toString 中获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53893857/