toString()
方法以 字符串 的形式返回 函数 的源代码。
示例
function sum(a,b){
return a + b;
}
// returns the source code of sum() function
console.log(sum.toString());
// Output:
// function sum(a,b){
// return a + b;
// }
toString 语法
toString()
方法的语法是
func.toString()
其中,func
是一个函数。
toString() 参数
toString()
方法不接受任何参数。
toString() 返回值
- 返回表示函数源代码的字符串。
示例 1:使用 toString() 方法
// function definition
function hello() {
console("Good morning.");
}
// prints the source code of the hello() function
console.log(hello.toString());
输出
function hello() { console("Good morning."); }
在上面的程序中,我们定义了函数 hello()
,然后调用 hello.toString()
形式的 toString()
方法。
toString()
方法返回 hello()
的全部源代码。
示例 2:带箭头函数的 toString()
// toString with arrow function
console.log((() => "Hello World!").toString());
输出
() => "Hello World!"
在上面的示例中,我们对 箭头函数 使用了 toString()
方法。
这里,该方法返回给定箭头函数的全部源代码。
另请阅读