{}
is both an expression (an empty object literal) and a statement (an empty block).
eval()
will try to parse its input as a statement.
If it isn't a "normal" statement (eg, an if
), it will be parsed as an expression statement, which evaluates an expression.
Therefore, {} + {}
is parsed as two statements (via ASI): {}; +{}
. The first statement is an empty block; the second statement is the unary +
operator which coerces an object to a number.
Coercing an object to a number involves calling toString()
(which returns "[object Object]"
), then parsing the result as a number (which it isn't).
eval()
then returns that as the value of the final statement.
Node wraps its REPL input in ()
to force it to be parsed as an expression:
// First we attempt to eval as expression with parens.
// This catches '{a : 1}' properly.
self.eval('(' + evalCmd + ')',
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…