为什么新的函数()返回的意见/ ** /在参数?

在chrome 47和nodejs v0.12中

new Function('myArg','return "my function body";')

给出以下结果:

 function anonymous(myArg /**/) { return "my function body" } 

为什么函数参数中有/ ** /的评论?

如以下Chromium问题所示 ,这是一种解决方法,可以解决包含不平衡块注释的边缘案例。 如V8源代码中所述 :

 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, ')', StringIndexOfJS) != -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})'; } 

这最初被添加到像下面这样的案例,并抛出一个错误:

 Function("/*", "*/){alert('bad');") 

这应该会导致语法错误,但是在添加/**/ ,会将其转换为:

 function anonymous(/*) { */){alert('bad'); } 

这相当于

 function anonymous(/*...*/) { alert('bad'); } 

因此没有语法错误。 改变之后,现在这个额外的评论变成:

 function anonymous(/*/**/) { */){alert('bad'); } 

这正确地给出了一个语法错误:

 Uncaught SyntaxError: Unexpected token *(…) 

源版本和原始错误报告 。