代码之家  ›  专栏  ›  技术社区  ›  MathGladiator

JavaScript、v8和函数打印

  •  2
  • MathGladiator  · 技术社区  · 15 年前

    在node.js(或v8/chrome)中,我可以依赖于使用字符串连接来获取函数后面的代码吗?

    var f = function(x) { return x; }
    console.log(f);
    

    显示“[函数]”,而

    console.log("" + f);
    

    显示“函数(x){return x;}”

    2 回复  |  直到 15 年前
        1
  •  2
  •   Christian C. Salvadó    15 年前

    好吧,我会说是的,因为你用的是V8引擎。

    字符串contatenation在幕后真正做的是调用 Function.prototype.toString

    var str = "" + f;
    

    大致相当于:

    var str = f.toString();
    

    此方法提供 依赖于实现

    但既然你是针对特定的实现,我想你不会有任何问题。

    如果你得到 "[object Function]" Object.prototype.toString 而是被执行 函数.prototype.toString 一个,例如:

    Object.prototype.toString.call(function () {}); // "[object Function]"
    
        2
  •  1
  •   Erik Corry    15 年前