Saturday, November 25, 2006

Creating Objects Using Object Literal

This method offers a much more convenient way to create objects without first predefining a constructor function. This method could be viewed as one of JavaScript's strength because of how it makes the creation of object so easy.

The object literal is actually a list of property-value pairs enclosed in curly brackets and separated by colon.

The syntax look thus

var myvarobject = {'propert1':'value1','property2':'value2','propertyN':'valuen'};

To see this in action lets see how it is used in creating objects.
So if i want to create a monitor object with the following properties: make,screensize and color, i will write:

var mymonitor = {'make':'Dell','screensize':'19inches','color':'graphite'};
and i have my object created.
Once this is done, i could check to see if the object was successfully created.
Writing:
alert(mymonitor.make) should display 'Dell'. Other properties of the object can thus be accessed.

No comments: