这是由于 REPL 如何评估输入,最终是:
(hi)()
添加额外的括号以强制它成为Expression:
// First we attempt to eval as expression with parens.
// This catches '{a : 1}' properly.
self.eval('(' + evalCmd + ')',
// ...
目的是将{...}
其视为Object
文字/初始化程序而不是块。
var stmt = '{ "foo": "bar" }';
var expr = '(' + stmt + ')';
console.log(eval(expr)); // Object {foo: "bar"}
console.log(eval(stmt)); // SyntaxError: Unexpected token :
而且,正如 leesei 所提到的,这已针对 0.11.x 进行了更改,它将仅包装{ ... }
而不是所有输入:
if (/^\s*\{/.test(evalCmd) && /\}\s*$/.test(evalCmd)) {
// It's confusing for `{ a : 1 }` to be interpreted as a block
// statement rather than an object literal. So, we first try
// to wrap it in parentheses, so that it will be interpreted as
// an expression.
evalCmd = '(' + evalCmd + ')\n';
} else {
// otherwise we just append a \n so that it will be either
// terminated, or continued onto the next expression if it's an
// unexpected end of input.
evalCmd = evalCmd + '\n';
}