(new Function(...))。toString()产生奇怪的结果

时间:2013-07-28 12:44:17

标签: javascript function google-chrome

尝试在Chrome和Firefox中运行以下内容

(new Function('a', 'return 1;')).toString()

Chrome会在参数列表的末尾添加/**/,除非没有参数。有什么理由吗?

两个浏览器似乎都将新创建的函数命名为“匿名”。它为什么命名呢?当然,它并没有给所有匿名函数赋予这个名称......如果你只是

(function(a) { return 1; }).toString()

然后你得到了function(a) { return 1; },这正是你所期望的。此外,我无法从函数内部调用anonymous - 因此它有一个名称,但它不包含在范围内?

1 个答案:

答案 0 :(得分:1)

看起来答案是V8 source code中与“不平衡块评论”相关的评论

function NewFunctionString(arguments, function_token) {
  var n = arguments.length;
  var p = '';
  if (n > 1) {
    p = ToString(arguments[0]);
    for (var i = 1; i < n - 1; i++) {
      p += ',' + ToString(arguments[i]);
    }
    // If the formal parameters string include ) - an illegal
    // character - it may make the combined function expression
    // compile. We avoid this problem by checking for this early on.
    if (%_CallFunction(p, ')', StringIndexOf) != -1) {
      throw MakeSyntaxError('paren_in_arg_string', []);
    }
    // If the formal parameters include an unbalanced block comment, the
    // function must be rejected. Since JavaScript does not allow nested
    // comments we can include a trailing block comment to catch this.
    p += '\n/' + '**/';
  }
  var body = (n > 0) ? ToString(arguments[n - 1]) : '';
  return '(' + function_token + '(' + p + ') {\n' + body + '\n})';
}