Calling toString on a javascript function returns source code

前端 未结 6 1282
梦如初夏
梦如初夏 2020-12-14 06:06

I just found out that when you call toString() on a javascript function, as in myFunction.toString(), the source code of that function is returned.

If y

6条回答
  •  悲&欢浪女
    2020-12-14 07:05

    You can use it as an implementation for multi-line strings in Javascript source.

    As described in this blog post by @tjanczuk, one of the massive inconveniences in Javascript is multi-line strings. But you can leverage .toString() and the syntax for multi-line comments (/* ... */) to produce the same results.

    By using the following function:

    function uncomment(fn){
      return fn.toString().split(/\/\*\n|\n\*\//g).slice(1,-1).join();
    };
    

    …you can then pass in multi-line comments in the following format:

    var superString = uncomment(function(){/*
    String line 1
    String line 2
    String line 3
    */});
    

    In the original article, it was noted that Function.toString()'s behaviour is not standardised and therefore implementation-discrete — and the recommended usage was for Node.js (where the V8 interpreter can be relied on); however, a Fiddle I wrote seems to work on every browser I have available to me (Chrome 27, Firefox 21, Opera 12, Internet Explorer 8).

提交回复
热议问题