The issue is a simple, yet annoying one. You want to access the property of an object, and work with that property value — perhaps calling a method on it, or accessing another property. The issue is that when an object property is undefined, errors happen. For example, if you're expecting a string or an array as a property value, the code would work fine if the property were initialized to an empty string, or an empty array respectively. The trick is, providing sane defaults on objects so that the clients using them don't blow up.
Showing posts with label object. Show all posts
Showing posts with label object. Show all posts
Thursday, February 13, 2014
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:
The code will run fine but it feels as though it shouldn't. The alternative notation is
This doesn't feel right either. I find its always better to be consistent, whatever notation is used.
For instance, here is a Javascript object using a keyword as an attribute name:
var my_obj = {id: 5, interface: "nic1"};
var my_obj = {"id": 5, "interface": "nic1"};
Labels:
attribute
,
instance
,
javascript
,
keyword
,
object
Subscribe to:
Posts
(
Atom
)