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

瀏覽器相容性

另見