Function.prototype.toString()

Baseline 广泛可用 *

此特性已相当成熟,可在许多设备和浏览器版本上使用。自 ⁨2015 年 7 月⁩以来,各浏览器均已提供此特性。

* 此特性的某些部分可能存在不同级别的支持。

toString() 方法是 Function 实例的方法,它会返回一个字符串,该字符串表示该函数的源代码。

试一试

function sum(a, b) {
  return a + b;
}

console.log(sum.toString());
// Expected output: "function sum(a, b) {
//                     return a + b;
//                   }"

console.log(Math.abs.toString());
// Expected output: "function abs() { [native code] }"

语法

js
toString()

参数

无。

返回值

表示函数源代码的字符串。

描述

Function 对象重写了从 Object 继承的 toString() 方法;它不继承 Object.prototype.toString。对于用户定义的 Function 对象,toString 方法返回一个包含用于定义函数的源代码文本段的字符串。

Function 要表示为文本值时(例如,当函数与字符串连接时),JavaScript 会自动调用 toString 方法。

如果 this 值对象不是 Function 对象,则 toString() 方法会抛出 TypeError 异常(“Function.prototype.toString called on incompatible object”)。

js
Function.prototype.toString.call("foo"); // throws TypeError

如果 toString() 方法在内置函数对象、由 Function.prototype.bind() 创建的函数或其它非 JavaScript 函数上调用,则 toString() 返回一个*原生函数字符串*,其外观如下:

function someName() { [native code] }

对于内建对象的方法和函数,someName 是函数的初始名称;否则,其内容可能是实现定义的,但始终会以属性名语法的形式出现,例如 [1 + 1]someName1

注意:这意味着对原生函数字符串使用 eval() 会导致语法错误。

如果 toString() 方法在一个由 Function 构造函数创建的函数上调用,toString() 会返回一个使用提供的参数和函数体合成的、名为“anonymous”的函数声明的源代码。例如,Function("a", "b", "return a + b").toString() 将返回:

function anonymous(a,b
) {
return a + b
}

自 ES2018 起,规范要求 toString() 的返回值必须与声明时使用的源代码完全相同,包括任何空格和/或注释 — 或者,如果出于某种原因主机无法获得源代码,则要求返回一个原生函数字符串。有关此修订行为的支持可以在兼容性表格中找到。

示例

比较实际源代码和 toString 的结果

js
function test(fn) {
  console.log(fn.toString());
}

function f() {}
class A {
  a() {}
}
function* g() {}

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

请注意,在 Function.prototype.toString() 修订后,当调用 toString() 时,实现不允许合成非原生函数字符串的函数源代码。该方法始终返回用于创建函数的精确源代码 — 包括上面gettersetter的示例。Function 构造函数本身具备合成函数源代码的能力(因此也是一种隐式eval())。

获取函数的源代码文本

可以通过将函数强制转换为字符串来获取函数的源代码文本 — 例如,通过将其包装在模板字面量中:

js
function foo() {
  return "bar";
}
console.log(`${foo}`);
// function foo() {
//   return "bar";
// }

此源代码文本是*精确*的,包括任何插入的注释(否则这些注释不会被引擎的内部表示存储)。

js
function foo /* a comment */() {
  return "bar";
}
console.log(foo.toString());
// function foo /* a comment */() {
//   return "bar";
// }

规范

规范
ECMAScript® 2026 语言规范
# sec-function.prototype.tostring

浏览器兼容性

另见