首页 > 其他 > 详细

Function.prototype.toString()

时间:2021-06-11 16:47:43      阅读:28      评论:0      收藏:0      [点我收藏+]

Function.prototype.toString()

toString() 方法返回一个表示当前函数源代码的字符串。

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] }"

语法

function.toString()

返回值

表示函数源代码的一个字符串

描述

Function对象覆盖了从Object继承来的toString 方法。对于用户定义的 Function 对象,toString方法返回一个字符串,其中包含用于定义函数的源文本段。

Function需要转换为字符串时,通常会自动调用函数的 toString 方法。

若 this 不是 Function 对象,则 toString() 方法将抛出 TypeError  ("Function.prototype.toString called on incompatible object") 异常,比如 Proxy 对象就会抛出异常。

Function.prototype.toString.call(‘foo‘); // TypeError

如果是在内置函数或由 Function.prototype.bind 返回的函数上调用 toString(),则toString() 返回原生代码字符串,如下

"function () {\n    [native code]\n}"

若是在由 Function 构造器生成的函数上调用 toString() ,则 toString() 返回创建后的函数源码,包括形参和函数体,函数名为 "anonymous"。

示例

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

Function.prototype.toString()

原文:https://www.cnblogs.com/yanjianjiang/p/14870352.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!