How to Simulate Multiple Pages with Tabbed Panels
How to Create a Mobile-Ready Page in Dreamweaver
How to Create a Data Table for Your Website

How to Create a Basic Object in JavaScript for HTML5 and CSS3 Programming

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.

  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
Add Searching Tools with Regular Expression Operators in JavaScript
How to Use JavaScript’s Event Object to Program with HTML
How to Use JavaScript Objects for HTML Integration
How to Use JavaScript Browser Objects to Manage the Application Environment
How to Use Core DOM Objects to Manage Application Content
Advertisement

Inside Dummies.com