Function.prototype.toString() - JavaScript 编辑

The toString() method returns a string representing the source code of the function.

The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.

Syntax

function.toString()

Return value

A string representing the source code of the function.

Description

The Function object overrides the toString method inherited from Object; it does not inherit Object.prototype.toString. For user-defined Function objects, the toString method returns a string containing the source text segment which was used to define the function.

JavaScript calls the toString method automatically when a Function is to be represented as a text value, e.g. when a function is concatenated with a string.

The toString() method will throw a TypeError exception ("Function.prototype.toString called on incompatible object"), if its this value object is not a Function object.

Function.prototype.toString.call('foo'); // TypeError

If the toString() method is called on built-in function objects or a function created by Function.prototype.bind, toString() returns a native function string which looks like

"function () {\n    [native code]\n}"

If the toString() method is called on a function created by the Function constructor, toString() returns the source code of a synthesized function declaration named "anonymous" using the provided parameters and function body.

It's also possible to explicitly get the string representation of a function using the + operator:

function foo() { return 'bar' }
console.log(foo + ''); // "function foo() { return 'bar' }"

Examples

Comparing actual source code and toString results

FunctionFunction.prototype.toString result
function f(){}
"function f(){}"
class A { a(){} }
"class A { a(){} }"
function* g(){}
"function* g(){}"
a => a
"a => a"
({ a(){} }.a)
"a(){}"
({ *a(){} }.a)
"*a(){}"
({ [0](){} }[0])
"[0](){}"
Object.getOwnPropertyDescriptor({
    get a(){}
}, "a").get
"get a(){}"
Object.getOwnPropertyDescriptor({
    set a(x){}
}, "a").set
"set a(x){}"
Function.prototype.toString
"function toString() { [native code] }"
(function f(){}.bind(0))
"function () { [native code] }"
Function("a", "b")
"function anonymous(a\n) {\nb\n}"

Specifications

Specification
ECMAScript (ECMA-262)
The definition of 'Function.prototype.toString' in that specification.

Browser compatibility

BCD tables only load in the browser

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:103 次

字数:7300

最后编辑:7年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文