HTML and CSS Reference
In-Depth Information
EXAMPLE 8.3 ( CONTINUED )
document.write("It is a " + toy.color + " " + toy.shape
+ ".<br />");
}
</script>
</head>
<body>
<script type = "text/javascript">
5
toy.display(); // Object method is called
6
toy.color="blue";
7
toy.display();
</script>
</body>
</html>
EXPLANATION
1 The Object() constructor is called with the new keyword to create an instance of a
new object. A reference to the new object is assigned to the variable, toy . We now
have a toy object.
2 The properties describe the characteristics or attributes of the object. Properties
act as variables for the object, but do not use the var keyword. The toy object's
name property is assigned “Lego” , its color property is assigned “red” , and its
shape property is assigned “rectangle” . The display property is assigned the name
of a function.
3 When the name of a function is assigned to a property, the property will serve as
a method for the object. The name of a function, printObject , is assigned to the
display property. Lines 5 and 7 demonstrate how to invoke the new method dis-
play() .
4 i tO j t ) function is defined. It will be used as a method for the toy object,
allowing the toy object to display its properties. Instead of display , we could use
the same name for this property; that is, toy.printObject = printObject . By giving the
property a different name, in this case, display , it is clear that the property is being
assigned a function name and that the object's method name is display , not print-
Object .
5
The object's display() method is called. Its function is to print the color and shape
properties of the toy object.
6
The global object called toy is available within the script. The value of the toy ob-
ject's color property is changed.
7
The object's display() method is called again showing that the value of the color
property has been changed to “blue” . The result is shown in Figure 8.4.
Search WWH ::




Custom Search