Tuesday, March 9, 2010

Javascript Object Attributes

I find the initialization of Javascript objects to be awkward when an attribute name is a Javascript keyword. It is bad practice to require attribute names with a keyword as an attribute name but sometimes it is unavoidable. For instance, when constructing an object to send along as parameters in an HTTP request.

For instance, here is a Javascript object using a keyword as an attribute name:
var my_obj = {id: 5, interface: "nic1"};
The code will run fine but it feels as though it shouldn't. The alternative notation is
var my_obj = {"id": 5, "interface": "nic1"};
This doesn't feel right either. I find its always better to be consistent, whatever notation is used.

No comments :

Post a Comment