Function.prototype.toString()
The toString()
method returns a string representing the
source code of the function.
Syntax
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
Function | Function.prototype.toString result |
---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Specifications
Specification |
---|
ECMAScript Language Specification # sec-function.prototype.tostring |
Browser compatibility
BCD tables only load in the browser