why ({}+{})="[object Object][object Object]"?
This question already has an answer here:
{}+{} is a block followed by an expression. The first {} is the block (like the kind you attach to an if statement), the +{} is the expression. The first {} is a block because when the parser is looking for a statement and sees { , it interprets it as the opening of a block. That block, being empty, does nothing. Having processed the block, the parser sees the + and reads it as a unary + . That shifts the parser into handling an expression. In an expression, a { starts an object initializer instead of a block, so the {} is an object initializer. The object initializer creates an object, which + then tries to coerce to a number, getting NaN .
In ({}+{}) , the opening ( shifts the parser into the mode where it's expecting an expression, not a statement. So the () contains two object initializers with a binary + (eg, the "addition" operator, which can be arithmetic or string concatenation) between them. The binary + operator will attempt to add or concatenate depending on its operands. It coerces its operands to primitives, and in the case of {} , they each become the string "[object Object]" . So you end up with "[object Object][object Object]" , the result of concatenating them.
Because of ambiguity. {} is an object but also a block boundary. Without () it is interpreted as the latter.
上一篇: JavaScript表达式
