这是由于REPL如何评估输入,最终是:
(hi)()
添加额外的括号以强制其为表达式:
// 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';
}