Changes

Jump to: navigation, search

JavaScript Object Basics

2,120 bytes removed, 20:32, 25 April 2007
Creating and using Object Instances
</pre>
== Creating and using Object Instances ==
In the previous section we learned how to create an object definition. It is important to note that, at this point, we have only described what the object will do, we have not actually created an object we can work with (this is known as an ''object instance''). Object instances are created using the ''new'' keywrod and are assigned to an object variable that will be used to reference the object. For example, in the following example we will create anew instance of the car object with the name myCar:
 
<pre>
carObject = new car ("Ford", "Focus", "Red");
</pre>
 
We have also passed through parameters to initialize the properties of the object (make, model and color).
 
Next we need to understand how to call a method on an object and access an object property. This is achieved by using what is called dot noation on the name of the object instance:
 
To access a property:
 
<pre>
objectInstance.propertyName
</pre>
 
To call a method of an object:
 
<pre>
objectInstance.methodName()
</pre>
 
In our example we have a method called displayCar() to the 3 properties of the object. Follwoing the above dot notation syntax we can call this method as follows:
 
<pre>
 
carObject.displayCar()
 
</pre>
 
We can also access a property, for example the color as follows:
 
<pre>
 
document.write ("The make property of myCar is " + myCar.make );
 
</pre>
 
Finally, we can also change one of the properties of an object instance:
 
<pre>
 
myCar.make = "BMW";
 
</pre>
 
Lets now bring all of this together in a complete example within an HTML page:
<pre>
<html>
<head>
<title>A Simple JavaScript Function Example</title>
<script language="JavaScript" type="text/javascript">
 
function car (make, model, color)
{
this.make = make;
this.model = model;
this.color = color
this.displayCar = displayCar;
}
function displayCar()
{
document.writeln("Make = " + this.make)
}
</script>
 
</head>
 
<script language="JavaScript" type="text/javascript">
myCar = new car ("Ford", "Focus", "Red");
myCar.displayCar();
myCar.make = "BMW";
myCar.displayCar();
</script>
 
</body>
</html>
</pre>
== Creating and using Object Instances ==

Navigation menu