fad*_*ire 13 javascript node.js
在chrome 47和nodejs v0.12中
new Function('myArg','return "my function body";')
给出以下结果:
function anonymous(myArg /**/) {
return "my function body"
}
Run Code Online (Sandbox Code Playgroud)
为什么函数参数中有注释/**/?
如下面的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})';
}
Run Code Online (Sandbox Code Playgroud)
这最初被添加到捕获如下的情况并抛出错误:
Function("/*", "*/){alert('bad');")
Run Code Online (Sandbox Code Playgroud)
这应该会导致语法错误,但在添加附加内容之前/**/,它将被转换为:
function anonymous(/*) {
*/){alert('bad');
}
Run Code Online (Sandbox Code Playgroud)
这相当于
function anonymous(/*...*/) {
alert('bad');
}
Run Code Online (Sandbox Code Playgroud)
因此没有语法错误.更改后,额外的评论现在变为:
function anonymous(/*/**/) {
*/){alert('bad');
}
Run Code Online (Sandbox Code Playgroud)
这正确地给出了语法错误:
Uncaught SyntaxError: Unexpected token *(…)
Run Code Online (Sandbox Code Playgroud)