JavaScript Tutorial: Objects

Here's a sample code of creating a object:

var myObj= new Object();   // creating a object
myObj.color1="red";       // creating a “property” of color1 and assign it "red"
window.alert(myObj.color1);

In the above code, myObj is a user created object, and it has color1 as one of its property. It is assigned the value “red”. One can create other properties by simply assiging it a value, such as “myObj.color2="blue"”.

JavaScript's Object property is basically like a keyed list in most languages. (aka: dictionary, hash, associative list) You can also access properties like a list:

myObj["color1"]="red";
window.alert("Color is: " + myObj["color1"]);

You can define a prototype of a object. That is, a object with predefined “properties” (elements). Example:

// define a object prototype “person” with properties: name, hair, height.
function person(a1,a2,a3) 
{ this.name   = a1;   // creates a property named “name”
  this.hair   = a2;
  this.height = a3;
}

// create objects “person”
mary=new person("Mary","blonde", "150");
jane=new person("Jane","brunette", "156");
window.alert("mary.namee is:" + mary.namee); // prints mary's name.

Reference: http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Guide:Working_with_Objects


See also:


Page created: 2005-05.
© 2005 by Xah Lee.
Xah Signet