JavaScript Objects
JavaScript is often misunderstood, with a bad reputation from the silly graphic effects of the past. JavaScript is truly a powerful language, especially when combined with AJAX and the server side of an application, but even on the client side JavaScript can accomplish much more than you would probably expect. Object-oriented JavaScript is one example, enabling us to create objects, extend intrinsic objects, and even create packages for our objects for easier management.
For this example, we’ll create three objects: Auto, Car, and Wheel. Each is a very simple object, but will be used to show how to create a basic package.
The Auto object is declared as a new object:
var Auto = new Object();
The Auto object doesn’t actually end here, though; it’s used as the parent of the Car object. Therefore, the Car object is a property of the Auto object, but separated into another file for easier management. (This concept is used in other object-oriented languages, but JavaScript isn’t often thought of in these terms.) Here’s the code for the Car object:
Auto.Car = new Object(); Auto.Car.color = "#fff"; Auto.Car.setColor = function(_color) { Auto.Car.color = _color; } Auto.Car.setColor("#333");
As you can see, the Car object is a child of the Auto object—a classic case of object hierarchy. This object has a property named color and a method to set it. We’re setting the color to gray, overwriting the default white. Keep this fact in mind until we serialize the object.
The next object, Wheel, is a child object of Car:
Auto.Car.Wheel = new Object(); Auto.Car.Wheel.color = "#000";
Wheel is a basic object, but it shows another layer to the object hierarchy. This object has one property called color, with a default value of black.
Let’s take a look at why these objects are significant and how their simple properties will be useful moving forward.