为什么函数变量(登录控制台时)不显示整个函数体?

Why function variable (when logged in console) does not show the whole function body?

我想知道为什么函数变量(当登录到控制台时)不显示整个函数体但 toString() 方法显示。

function person(name) {
    this.f_name = name;

    return function print_name (){
            alert("Your Name Is: " + this.f_name);
        }
  }

var myfunc = person('James');

  console.log(myfunc); //-> function print_name()

  console.log(myfunc.toString()); // ->"function print_name(){
        alert("Your Name Is: " + this.f_name);
    }"

console.log 无法打印的所有内容都会得到相应的 toString 调用方法 仍然 能够表示/总结 最重要的 关于函数的详细信息。

您可以在此处阅读:MDN - 特别是这句话:

the toString method returns a string representation of the object in the form of a function declaration. That is, toString decompiles the function, and the string returned includes the function keyword, the argument list, curly braces, and the source of the function body [1].

这基本上是说您不需要了解调试的内部机制,因为您可以查看源代码(在开发工具或编辑器中),所以它不会打印所有内容 - 只需打印那些需要/方便程序员当时知道。

[1] - 我实际上不知道为什么会有这条线或者我误解了。 (正如下面评论中@deceze所指出的)

我运行在一些浏览器的dev tools中有如下代码对比:

console.log(function(a, b) { return a + b; });

输出:

  • Firefox:function () - w/o 个参数但可点击以查看更多信息
  • Chrome: function (a, b) { return a + b } w/ arguments,点击它会带你到 devtools 中的一个窗格,其中包含函数的源代码
  • Safari:function (a, b) { return a + b; },带参数,点击什么都不做

因为我在 Mac 我无法在 IE 中测试它,但输出很有趣。 更多的是开发人员偏爱哪个浏览器 he/she 开发,因为这只是一个开发 API 而不是跨浏览器应该一致的东西。