Why does the second line of code produce an error but not the third?
{ foo: 'bar' } // => 'bar'
{ "foo": 'bar' } // => SyntaxError: Invalid label
({ "foo": 'bar' }) // => { foo: 'bar' }.
Why does the second line of code produce an error but not the third?
{ foo: 'bar' } // => 'bar'
{ "foo": 'bar' } // => SyntaxError: Invalid label
({ "foo": 'bar' }) // => { foo: 'bar' }.
言語仕様の関連部分はhttp://es5.github.com/#x12.4です。
ExpressionStatement : [先読み ∉ {
{
,function
}] 式;
{
先読み部分とは、 orで始まらない場合、ステートメントが期待される場所に何かが現れた場合にのみ、何かが式として扱われることを意味しますfunction
。
{ foo: 'bar' }
'bar'
labelの式 statement を含むステートメントのブロックですfoo
。ラベルを使用すると、名前付きループに出入りできますbreak
がcontinue
、ループだけでなく、任意のステートメントに付けることができます。
{ "foo": 'bar' }
パーサーはこれの解析を開始し、式"foo"
を見つけて二項演算子を探しますが:
、有効な二項演算子ではないため、構文例外で失敗します。
({ "foo": 'bar' })
ここで、括弧は式のコンテキストに入ります。したがって、{
は、ブロックの開始としてではなく、オブジェクト コンストラクターの開始として扱われます。