Welcome!

Kurt Cagle

Subscribe to Kurt Cagle: eMailAlertsEmail Alerts
Get Kurt Cagle via: homepageHomepage mobileMobile rssRSS facebookFacebook twitterTwitter linkedinLinkedIn


Related Topics: RIA Developer's Journal, AJAX World RIA Conference

RIA & Ajax: Article

Real-World AJAX Book Preview: Working with JavaScript Objects

Real-World AJAX Book Preview: Working with JavaScript Objects

This content is reprinted from Real-World AJAX: Secrets of the Masters published by SYS-CON Books. To order the entire book now along with companion DVDs for the special pre-order price, click here for more information. Aimed at everyone from enterprise developers to self-taught scripters, Real-World AJAX: Secrets of the Masters is the perfect book for anyone who wants to start developing AJAX applications.

Working with JavaScript Objects
Objects are possibly an odd place to start when talking about JavaScript, but if you understand exactly how JavaScript handles objects, you'll have one of the most powerful tools possible for working with AJAX-based components.

An object in JavaScript corresponds to hash tables or associative arrays in other languages. In such a hash table, you can store variable values by a given name, using a notation similar to that used for arrays. For instance, suppose that you wanted to store information about a pop-up balloon that would hover over a given point. For now, keep this simple by only worrying about two properties - the width of the balloon and the text message inside. Using objects, you'd represent this as follows:

var balloon = new Object();
balloon["width"] = 150;
balloon["message"] = "This is a cool message.";

Once defined, you can retrieve the balloon's message property by retrieving its name:

print(balloon["message"])

You can also use such objects as Lvalues in exactly the same way that you would use variables:

balloon["left"] += 1; // Increments the left property by one
balloon["left"]++; // does the same thing.

This particular notation works for any string value, no matter how complex. However, if the string in fact forms a valid variable name (that is, it's made up of alphanumeric characters or the underscore character), you can also simplify things pretty dramatically by utilizing the dot notation ".", which roughly corresponds to Java's object property and method accessor. Thus, the same example as above could be rendered as:

var balloon = new Object();
balloon.width = 150;
balloon.message = "This is a cool message.";
print(balloon.message);
balloon.left +=1;
balloon.left++;

The dot notation and hash key notation are mutually compatible - you can define a property one way and access it the other. This comes in handy in situations where you may have objects that others have defined (such as DOM elements) and you want to do some introspection on the properties. The construct for (key in obj) will let you retrieve each of the keys that are defined on the object and from them you can then determine the property values themselves:

for (key in balloon){
      print(key+":"+balloon[key]);
      }
width:152
message:"This is a cool message"

You can also get the values directly using the slightly different for each (value in obj) construct:

for each (value in balloon){
      print(value);
      }
152
"This is a cool message"

As if this wasn't enough, there's still another way to create objects, one that's actually used quite extensively in AJAX implementations. This method uses braces notation along with a sequence of key value pairs (a sequence is defined as a set of evaluated statements separated by commas). Thus, the balloon object above could be defined as well by:

var balloon = {left:150,message:"This is a cool message!"}
print(balloon.left);
150
Print(balloon.message);
"This is a cool message!"

It's important to understand that in this particular case the keys are treated automatically as strings, so do not quote as such. Of course, this also means that you can't use variables to hold key names here (the variable name will be treated as the key, not the variable contents), but this raises some serious coding issues that are probably best avoided.

The braces notation has the benefit of brevity and works a little more consistently with the current best practices on functions (which will be covered in greater detail in the next section), but in general the braces notation (and the concept that it implies of creating just-in-time objects) should be used judiciously because it inhibits code reuse.

Note that the contents of a given object don't have to be just scalar values (i.e., numbers and strings) but can in fact be other objects, arrays, and functions. For instance, you could create a new balloon object that lets you specify the origin of the balloon and its bounding box (the smallest rectangle that completely surrounds the balloon):

var balloon = {
position:{x:100,y:200},
      boundingBox:{width:250,height:120},
      message: "This is an even cooler message.",
      isVisible: false
      }

In this case, it's worthwhile observing first that braces notation objects can be defined over multiple lines and ignore carriage returns and other white space in the boundaries of those braces.

This consequently makes it easier to create such objects without having lots of explicit assignment statements that can be more ambiguous.

This notation also should give a hint about how complex objects are handled. Because objects can return other objects, you can use either dot notation or hash key notation to be able to retrieve information about a particular field:

print("The message is at " + balloon.position.x + "," balloon.position.y);
The message is at 100,200
print("This bounding box is " + balloon["boundingBox"]["width"] +" pixels wide by
" + balloon.boundingBox["width"] + " pixels high.");

The boundingBox is 250 pixels by 120 pixels.

Finally notice that the new keyword is essential when creating such objects - you are in essence creating a new object from an Object class, rather than working with the base Object object. This holds true for the other core datatypes as well. For instance, to create a new array object (that derives from the Object object), you'd use the expression:

var myArr = new Array();

This holds true for all other base types as well, though in general the use of the new keyword is handled implicitly if an object operator is used. For instance:

var o = new Object();
var o = {};
var a = new Array(1,2,3);
var a = [1,2,3];
var s = new String("This is a string");
var s = "This is a string";
var r = new RegExp(\w{3});
var r = /\w{3}/;

You can also create objects from external libraries, though this will be implementation-dependent, and covered in much greater depth later in this chapter.

This content is reprinted from Real-World AJAX: Secrets of the Masters published by SYS-CON Books. To order the entire book now along with companion DVDs, click here to order.

More Stories By Kurt Cagle

Kurt Cagle is a developer and author, with nearly 20 books to his name and several dozen articles. He writes about Web technologies, open source, Java, and .NET programming issues. He has also worked with Microsoft and others to develop white papers on these technologies. He is the owner of Cagle Communications and a co-author of Real-World AJAX: Secrets of the Masters (SYS-CON books, 2006).

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.