How do JavaScript members/properties work?
What is the difference between an object create with this syntax: { prop1: val1, prop2: val2 }
, and an object created with this syntax: { 'prop1': val1, 'prop2': val2 }
?
And also, does the following code work?
var val1 = 10, val2 = 15;
var tmp1 = { prop1: val1 };
var tmp开发者_运维问答2 = { 'prop2': val2 };
alert(tmp1['prop1']); // I expect 10
alert(tmp2['prop2']); // I expect 15
P.S.: Sorry, I couldn't come up with a better title for my question. That reflects my lack of knowledge of JavaScript.
There is no difference in your examples. You would need the quotes if any of your property names had spaces or special characters or were otherwise not a valid identifier:
{ prop1 with spaces: val1, 6prop2$-^: val2 } // illegal
{ 'prop1 with spaces': val1, '6prop2$-^': val2 } // correct
No difference at all, although the string version lets you use characters that are not valid characters for identifiers.
You can do this with strings:
{ 'prop-1': val1, 'prop-2': val2 }
But not as identifiers:
{ prop-1: val1, prop-2: val2 }
And yes, that code works.
精彩评论