gpt4 book ai didi

javascript - 为什么 JavaScript 函数的 toString 是实现依赖的?

转载 作者:行者123 更新时间:2023-11-29 10:41:36 25 4
gpt4 key购买 nike

来自EcmaScript 5 specification

15.3.4.2 Function.prototype.toString( )

An implementation-dependent representation of the function is returned. This representation has the syntax of a FunctionDeclaration. Note in particular that the use and placement of white space, line terminators, and semicolons within the representation String is implementation-dependent.

为什么它依赖于实现?让它输出由函数原始代码组成的标准化字符串应该不难。此外,我能想到的原因(例如优化)似乎并没有被过度使用,因为几乎所有浏览器都将原始代码作为 toString 的结果。

如果 toString 不依赖于实现并因此被标准化为函数的原始代码(新行等以标准方式处理),它不会使可以在 JSON 上包含函数吗?

我确实意识到 JSON,尽管它的名字,是独立于 JavaScript 的,因此函数不应该是它的一部分。但这种方式理论上可以将函数作为字符串传递给它,而不会失去跨浏览器支持。

最佳答案

在内部,Function.prototype.toString() 必须获取函数的函数声明代码,它可能有也可能没有。根据 MDN 页面,FF 以前是反编译函数的,现在它把声明和函数一起存储,所以它不需要反编译。

Since Gecko 17.0 (Firefox 17 / Thunderbird 17 / SeaMonkey 2.14), Function.prototype.toString() has been implemented by saving the function's source. The decompiler was removed

* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/toString

反编译它需要额外的工作。存储它需要额外的内存。给定的 ECMAscript 实现可能有不同的资源要求。

此外,如果它被反编译,那首先取决于它是如何存储的。引擎可能无法返回原始注释,因为它在计算函数时没有存储它们。或者,如果引擎折叠它们,空格/换行符可能会有所不同。或者引擎可能已经优化了代码,例如通过忽略 unreachable code,使得无法在 toString() 调用中返回该代码。

...some engines omit newlines. And others omit comments. And others omit "dead code". And others include comments around (!) function. And others hide source completely...

* http://perfectionkills.com/state-of-function-decompilation-in-javascript/

这些只是为什么 Function.prototype.toString() 依赖于实现的几个原因。

关于javascript - 为什么 JavaScript 函数的 toString 是实现依赖的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28004608/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com