Function.prototype.toString()
Function
实例的 toString()
方法返回一个表示该函数源代码的字符串。
¥The toString()
method of Function
instances returns a string representing the source code of this function.
Try it
语法
参数
返回值
描述
¥Description
Function
对象重写了从 Object
继承的 toString()
方法;它不继承 Object.prototype.toString
。对于用户定义的 Function
对象,toString
方法返回一个字符串,其中包含用于定义函数的源文本段。
¥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.
当 Function
被表示为文本值时,JavaScript 会自动调用 toString
方法,例如 当函数与字符串连接时。
¥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.
如果 this
值对象不是 Function
对象,则 toString()
方法将引发 TypeError
异常 ("在不兼容的对象上调用 Function.prototype.toString")。
¥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"); // throws TypeError
如果在内置函数对象、由 Function.prototype.bind()
创建的函数或其他非 JavaScript 函数上调用 toString()
方法,则 toString()
返回一个原生函数字符串,如下所示
¥If the toString()
method is called on built-in function objects, a
function created by Function.prototype.bind()
, or
other non-JavaScript functions, then toString()
returns a
native function string which looks like
function someName() { [native code] }
对于内部对象方法和函数,someName
是函数的初始名称;否则其内容可能是实现定义的,但始终采用属性名称语法,如 [1 + 1]
、someName
或 1
。
¥For intrinsic object methods and functions, someName
is the initial name of the function; otherwise its content may be implementation-defined, but will always be in property name syntax, like [1 + 1]
, someName
, or 1
.
注意:这意味着在原生函数字符串上使用
eval()
肯定会出现语法错误。¥Note: This means using
eval()
on native function strings is a guaranteed syntax error.
如果在 Function
构造函数创建的函数上调用 toString()
方法,则 toString()
使用提供的参数和函数体返回名为 "anonymous" 的合成函数声明的源代码。例如,Function("a", "b", "return a + b").toString()
将返回:
¥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. For example, Function("a", "b", "return a + b").toString()
will return:
function anonymous(a,b ) { return a + b }
自 ES2018 起,规范要求 toString()
的返回值与其声明的源代码完全相同,包括任何空格和/或注释 - 或者,如果主机由于某种原因没有可用的源代码,则需要返回 原生函数字符串。可以在 兼容性表 中找到对此修订行为的支持。
¥Since ES2018, the spec requires the return value of toString()
to be the exact same source code as it was declared, including any whitespace and/or comments — or, if the host doesn't have the source code available for some reason, requires returning a native function string. Support for this revised behavior can be found in the compatibility table.
示例
比较实际源代码和 toString 结果
¥Comparing actual source code and toString results
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()
时,永远不允许实现合成不是原生函数字符串的函数源。该方法始终返回用于创建函数的确切源代码 - 包括上面的 getter 和 setter 示例。Function
构造函数本身具有合成函数源代码的能力(因此是隐式 eval()
的一种形式)。
¥Note that after the Function.prototype.toString()
revision, when toString()
is called, implementations are never allowed to synthesize a function's source that is not a native function string. The method always returns the exact source code used to create the function — including the getter and setter examples above. The Function
constructor itself has the capability of synthesizing the source code for the function (and is therefore a form of implicit eval()
).
获取函数的源文本
¥Getting source text of a function
可以通过将函数的源文本强制转换为字符串来获取函数的源文本 - 例如,通过将其封装在模板文字中:
¥It is possible to get the source text of a function by coercing it to a string — for example, by wrapping it in a template literal:
function foo() {
return "bar";
}
console.log(`${foo}`);
// function foo() {
// return "bar";
// }
该源文本是准确的,包括任何散布的注释(否则引擎的内部表示不会存储这些注释)。
¥This source text is exact, including any interspersed comments (which won't be stored by the engine's internal representation otherwise).
function foo /* a comment */() {
return "bar";
}
console.log(foo.toString());
// function foo /* a comment */() {
// return "bar";
// }
规范
Specification |
---|
ECMAScript Language Specification # sec-function.prototype.tostring |
浏览器兼容性
BCD tables only load in the browser
也可以看看
¥See also