javascript - Unusual object definition -
i stumbled upon this, eyes, strange object declaration.
var config = {}; { config.foo = 'foo'; config.bar = 'bar'; };
it works, though have guessed wouldn't.
confused open console in chrome devtools, , enter:
var = {}; // => undefined
nothing strange far. enter:
{ a.b = 'b'; } // => uncaught syntaxerror: unexpected token .
ok, hmm ... wasn't supposed work? try, without separate evaluations of statements:
var = {}; {a.b = 'b'}; // => "b"
hmm, no syntaxerror thrown. , if evaluate a, can see defined intended.
a; // => object {b: "b"}
what happening? i've tried google it, don't know search for, , lack kind of knowledge figure out happening. can please explain it?
to add on has been said..
in javascript, object literal:
{x: 3}
and block:
{ console.log("hello, world!"); }
any statement can go inside of block.
the trouble is, {x: 3}
interpreted block, on own.
to make object literal far javascript concerned, have surround in parenthesis:
({x: 3})
that's chrome devtools whenever sees input object literal isn't surrounded. it'll make {x: 3}
({x: 3})
, {y: 15, z: 'kar'}
({y: 15, z: 'kar'})
, , on.
the trouble is, it'll blocks. turns {x = y}
({x = y})
, of course syntax error. javascript thinks you're giving object literal, doesn't expect statement.
however, devtools ignores rule of turning un-parenthesized object literals parenthesized object literals if have statement before object literal. works:
console.log('bananas!'); {x = y}
and statement doesn't really need statement. there needs semicolon before block:
;{x = y}
it's weird quirk of chrome devtools. it's supposed people new coding javascript (and object literals), can confusing people are experienced!
Comments
Post a Comment