• 首页
  • vue
  • TypeScript
  • JavaScript
  • scss
  • css3
  • html5
  • php
  • MySQL
  • redis
  • jQuery
  • Function.prototype.toString()

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

    语法

    function.toString()
    

    返回值

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

    描述

    Function对象,toString方法返回一个字符串,其中包含用于定义函数的源文本段。

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

    this不是Function 对象,则toString()方法将抛出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}"