Question about Javascript Shorthand object quotes in the key
I'm pretty new to javascript and am wondering about quoting the keys in object shorthand
So I am using the OpenLayers js library and many of the object constructors take {options}
as the argument for setting different variables, callbacks, etc.
In my code I have a bunch of control objects which are used to manipulate the map and what-not
controls = {
navigation : new OpenLayers.Control.Navigation({'autoActivate' : false}),
zoom_out_box : new OpenLayers.Control.ZoomBox({
alwaysZoom : true,
out : true
}),
...
};
In some of their examples they use single quotes for the keys and others they won't {'ascending':false}
or {visibility: false}
.
I thought that maybe it had to do with reserved words or functions vs variables but I can add functions to my zoom box:
controls= {
zoom_out_box : new OpenLayers.Control.ZoomBox({开发者_Python百科
if : function(e){alert('blah');}
}),
zoom_out_box_2 : new OpenLayers.Control.ZoomBox({
'if' : function(e){alert('blah');}
})
};
I test it with an onlclick="controls.zoom_out_box.if(this)"
and it alerts fine and I get no warnings or errors in firebug.
So whats the difference in the quoting?
You can use non-identifiers as keys in a JavaScript object, in which case, the quotes are required:
var obj = { 'not-an-identifier': 42 };
In the case where an identifier is quoted, it's just a matter of style/preference/convention.
As a side note, non-identifiers must always be accessed using the square-bracket/array-style notation (obj['not-an-identifier']
), rather than the dot (.
) notation.
The currently accepted answer is incorrect:
You can use non-identifiers as keys in a JavaScript object, in which case, the quotes are required
The quotes aren’t required if you use a numeric literal as a property name.
From Unquoted property names / object keys in JavaScript, my write-up on the subject:
Quotes can only be omitted if the property name is a numeric literal or a valid identifier name.
[…]
Bracket notation can safely be used for all property names.
[…]
Dot notation can only be used when the property name is a valid identifier name.
I also made a tool that will tell you if any given property name can be used without quotes and/or with dot notation. Try it at mothereff.in/js-properties.
精彩评论