HTML5 and CSS3 All-in-One For Dummies
Book image
Explore Book Buy On Amazon

JavaScript makes it trivially easy to build an object for HTML5 and CSS3 programming. Because a variable can contain any value, you can simply start treating a variable like an object and it becomes one.

image0.jpg

Take a look at the following code:

 //from basicObject.html //create the critter var critter = new Object(); //add some properties critter.name = "Milo"; critter.age = 5; //view property values alert("the critter's name is " + critter.name);

The way it works is not difficult to follow:

  1. Create a new Object.

    JavaScript has a built-in object called Object. Make a variable with the new Object() syntax, and you'll build yourself a shiny, new standard object.

  2. Add properties to the object.

    A property is a subvariable. It's nothing more than a variable attached to a specific object. When you assign a value to critter.name, for example, you're specifying that critter has a property called name and you're also giving it a starting value.

  3. An object can have any number of properties.

    Just keep adding properties. This allows you to group a number of variables into one larger object.

  4. Each property can contain any type of data.

    Unlike arrays where it's common for all the elements to contain exactly the same type of data, each property can have a different type.

  5. Use the dot syntax to view or change a property.

    If the critter object has a name property, you can use critter.name as a variable. Like other variables, you can change the value by assigning a new value to critter.name or you can read the content of the property.

If you're used to a stricter object-oriented language, such as Java, you'll find JavaScript's easy-going attitude quite strange and maybe a bit sloppy. Other languages do have a lot more rules about how objects are made and used, but JavaScript's approach has its charms. Don't get too tied up in the differences. The way JavaScript handles objects is powerful and refreshing.

About This Article

This article is from the book:

About the book author:

Andy Harris taught himself programming because it was fun. Today he teaches computer science, game development, and web programming at the university level; is a technology consultant for the state of Indiana; has helped people with disabilities to form their own web development companies; and works with families who wish to teach computing at home.

This article can be found in the category: