An Object Lesson In JavaScript - Room With A View (Page 7 of 9 )
Just as you can pass parameters to an object, it's also possible to pass it another object. Consider the following example, which consists of two object constructors - the second one is set up to accept an object as parameter.
<script language="JavaScript">
// Room object
// accepts area (sq. ft.) and colour (walls) as parameters
function Room(area, colour)
{
this.area = area;
this.colour = colour;
}
// House object
// accepts price as parameter
function House(price, room)
{
this.price = price;
this.obj = room;
}
</script>
Here's how you might use it:
<script language="JavaScript">
Kitchen = new Room(500, "white");
DiningRoom = new Room(600, "white");
RedGables = new House(89000, Kitchen);
alert(RedGables.obj.area);
</script>
In this case, the newly-created instance of the Room
object, "Kitchen", is passed to the House object "RedGables". Using a hierarchical structure, it is possible to drill down through the House object to the Room object and obtain the value of a specific object property. This is similar to the manner in which many DOM objects are accessed.
Next: Construction Crew >>
More JavaScript Articles
More By Vikram Vaswani, (c) Melonfire