【问题标题】:JavaScript .toString() default valueJavaScript .toString() 默认值
【发布时间】:2016-02-09 18:10:59
【问题描述】:
我正在尝试编写一个将另一个函数作为参数的函数(我们可以假设另一个函数的 toString 方法将始终被覆盖以返回自定义值)并返回函数的原始 toString 值。
function foo () {}
foo.toString = function () {
return 'abc'; }
如何恢复函数的 toString 方法,使其再次返回“function foo () {}”?
【问题讨论】:
标签:
javascript
function
tostring
【解决方案1】:
由于toString是一个原型属性,当你delete它时,它会恢复为默认值:
function foo () {}
foo.toString = function () {
return 'abc';
}
document.write('<pre>'+JSON.stringify(String(foo),0,3));
delete foo.toString
document.write('<pre>'+JSON.stringify(String(foo),0,3));