MSc-IT Study Material
June 2010 Edition

Computer Science Department, University of Cape Town

The JavaScript object model

Introduction to the JavaScript object model

It is practically impossible to write useful JavaScript without using object properties and methods — even though many novice programmers do not realise they are making use of JavaScript objects.

Consider the following line of code:

        document.write( "Sorry, that item is out of stock" );
      

The above line illustrates the use of many important object concepts, since it involves creating a new object ("Sorry..." is an instance built from the String constructor function), passing a reference to this new object as an argument to a method of another object (write() is a method of the document object).

JavaScript has a powerful and flexible object model. Unlike the Java programming language, JavaScript is a class-less language: the behaviour and state of an object is not defined by a class, but rather by other objects (in the case of JavaScript, this object is called the object's prototype. While this major difference to languages such as Java and C++ often leads people to conclude that the JavaScript object model is a simple one, the JavaScript object model is powerful enough to allow a JavaScript programmer to extend its single inheritance abilities to allow for implementations of multiple inheritance, but also most of the functionality that JavaScript is considered to have "missing". All of this may also be done dynamically, at runtime — in other words, prototypes are defined while the JavaScript programme is executing, and can be updated with new methods and properties as and when they are required, and not only at compile time as with languages such as Java.

As you progress through this part of the unit, you will both learn new ways to use and define your own objects and constructor, and also you will come to more fully understand many JavaScript programming concepts you have learned up to now. The remainder of this introduction provides a more detailed overview of the JavaScript object model presented briefly in the first JavaScript unit.

Objects in JavaScript

A software system is considered to be a set of components — objects — that work together to make up the system. Objects have behaviour (defined by functions and methods) that carries out the system's work, and state, which affects its behaviour. As we previously mentioned, objects may be created and used by programming a constructor function to create objects, or instances. A constructor is merely a JavaScript function that has been designed to be used with the new keyword. The constructor defines what properties an object should have (the object's state), as well as its methods.

Programming an object involves declaring instance variables to represent the object's state, and writing instance methods that implement behaviour. The separate parts of an object's state are often called its properties. Thus, you might have a bank account object which had properties such as holder of account, address of holder, balance and credit limit; its methods would include the likes of credit, debit and change address.

JavaScript represents functions (which are used to implement methods, and to create objects) as data of type Function (notice the capital F), so in fact there is less difference between data properties and functions (or methods) than in most other object-based programming languages. Functions can be passed and stored in variables, and any function stored in a particular variable can be executed when required.

An object is said to encapsulate its state (often simply called its data) and its behaviour. In the case of JavaScript, this means that each object has a collection of properties and methods.

A JavaScript object can inherit state and behaviour from any other object. This object is called a prototype.

An object can obtain properties and methods from the constructor function from which the object is created; from its prototype, through inheritance; and from any properties and methods added separately to the object after it has been constructed (remember that Functions are just data that can be freely assigned to variables, as and when required). Two objects made from the same constructor function can have different properties and methods from each other, since extra properties and methods can be added to each object after they have been created.

Associated with inheritance is the separate concept of polymorphism, the ability to call a method on an object irrespective of the constructor function used to create the object, and expect the appropriate method to be called for the given object. For example, there can be two constructor functions, Square() and Circle(), which create objects representing squares and circles, respectively. The constructor can create these objects so that they each have an area() method that returns the area of the object. Of course, the method will operate differently for square and circle objects, but any variable holding either a square or a circle object can have the area method called on it, and polymorphism will ensure that the correct area method is called for the appropriate object.

Naming conventions

Although it can initially seem rather pedantic, the following naming convention is used throughout this unit, and is widely used in various programming standards. Using a standard convention helps a programmer to understand the code that they are reading, and you are advised to adopt this convention in your own programming.

All words of a constructor are spelt with an initial capital letter. Examples include:

  • Document

  • Form

  • Triangle

  • Array

  • String

  • BankAccount

  • CreditCard

The first word in an instance (object) name is spelt with all lower case letters; all subsequent words making up the object name are spelt with an initial capital, as per usual. Examples include:

  • document

  • ageField

  • triangle1

  • nameArray

  • customerAccount1

The first word of a method name is spelt in lower case; all subsequent words making up the object name are spelt with initial capitals. Examples include:

  • area

  • setBalance

  • isGreaterThan

  • postTransaction

The first word of a property is spelt in lower case; all subsequent words making up the object name are spelt with initial capitals. Examples include:

  • triangle1.colour

  • width

  • firstName

  • addressLine1

  • value

  • fontSize

Exercise 3

Which of the following are constructors:

  • door1

  • House

  • MotorCar

  • homeHampus

You can find a discussion of this Exercise at the end of the unit.

Creating objects and variables referring to objects

Objects are created in a number of ways, although the most common is by the use of the new operator. This is a unary, prefix operator, which means it is placed before a single operand. The new operator should be followed by a constructor function.

Here are some examples:

        new Object();

        var accountNumbers = new Array( 5 );
        var firstName = new String( "Jose" );
      

Where is the object created?

Sufficient free memory is located in which to create the new object. The new operator returns a reference to the location in memory where the new object has been created. In the first of the three examples above (new Object();), no variable is assigned the result of the object creation, therefore there is no way for the JavaScript programmer to refer to this object later in the programme. In almost all cases, a variable will be assigned the reference to the location of the newly created object.

In the second example above the reference variable accountNumbers is assigned the reference to the location of the newly created Array object.

Note

Variables do not store objects, they store a reference to the object located elsewhere in memory.

Creating String objects

Although the following way of creating String objects is perfectly acceptable JavaScript:

        var firstName = new String( "Jose" );
 

it is usually much more convenient to used the special syntax provided for creating String literal objects. The same result could be achieved with the following statement:

        var firstName = "Jose";
 

String objects can be created in two different ways because the creation of String objects is such a common feature of programming that the developers of the JavaScript language provided this second, simpler syntax especially for Strings.

Creating Function objects

Just as the creation of Strings is so common the JavaScript developers provided a special syntax, the same has been done for make the creation of Function objects easier. As you will know from earlier units a function object can be created in the following way:

        function myFunction( arg1,arg2, -, argN )

        {
        //function statements go here
        }
 

Functions are themselves objects (of the type Function), and can be created in the same way as objects using the Function constructor:

        var myFunction = new Function( arg1, arg2, -, argN, "//function statements go here");
	

In most cases the former way of creating Function objects is more straightforward.

Object properties and methods

Objects have both data properties and methods (function properties). Often a property of one object is an object in its own right (or perhaps another kind of collection, such as an array). An example is the forms[ ] array property of the document objects — this property contains details (i.e. an array) for all the forms on a Web page.

Properties

Variables (data) that "belong" to objects are called properties. In earlier units you have seen examples of properties, such as an array's length property:

        var myArray = new Array( 5 );

        alert( "length of array is: " + myArray.length );
 

In the example above the length property of the myArray object is accessed by the dot notation:

        myArray.length
 

Methods

Methods are object properties containing functions. In earlier units you have seen examples of methods, for example the reverse method of an array:

        var myArray = new Array( 3 );

        myArray[0] = 11;
        myArray[1] = 22;
        myArray[2] = 33;

        alert( myArray.reverse() );
	

In the example above the reverse() method of the myArray object is invoked by the dot notation:

        myArray.reverse()
	

As can be seen, the only difference from (data) properties is when methods are invoked with the use of the () (parentheses) operator — this is a special operator expecting a variable holding a Function object to the left, and optional operands (the function arguments) between the parentheses.

It is important to realise that methods are properties, but ones which can also be invoked since they are properties that hold Function objects.

The 'dot' syntax

What is sometimes known as dot notation is used to indicate which properties an object owns. Ownership of properties can exist to any number of levels deep, and the dot notation can be used at every level. fine.

The use of the full stop (dot) can be thought of as meaning "the thing on the right belongs to the object (named collection) on the left". The general form for properties and methods to be invoked is as follows:

    <object>.<property>
    <object>.<method>()
	

Common examples include:

    var myArray = new Array( 3 ) ;
    myArray.length;

    var catpic = new Image();
    catpic.src = "images/cartoons/sillycat1.gif";
	

In each of the above examples, the dot syntax is used to refer to a named piece of data (property) of an object. So we can refer to the length property belonging to the Array object myArray, and the src property of the Image object catpic.

We can see extensive use of the dot notation in the line:

    document.forms[0].age.value;
	

This line refers to the value property of the age property (itself an object) of the form object at index 0 of the forms[] array object of the document object. Code using such a reference to the value of a form's text input box is as follows:

        <script> <!--

        function showAge()

        {
        var newAge = document.forms[0].age.value;
        alert("Age is: " + newAge );
        }
        // --> </script>

        <form>
        Enter age:
        <INPUT TYPE="text" NAME="age" SIZE=10>
        <INPUT TYPE="button" NAME="button1" 
           VALUE="click me" SIZE=10 onClick="showAge()">

        </form>
 

The browser output is:

Variables are properties

When a JavaScript programme is being executed. a special object, called the 'global' object, is created. The global object exists until the programme terminates. All variables of a JavaScript programme are properties of this global object.

Functions are methods

In the same way that all variables of a JavaScript programme are in fact properties of the global object, likewise all the functions of a JavaScript programme are methods of the global object.

Functions are properties too

Since methods are just properties that hold Function objects, functions, being methods of the global object, are also stored in properties of the global object.

Some important JavaScript objects

Although you have been programming with objects for some weeks in JavaScript, you may not have been aware of some of the objects you have been working with. This section briefly describes important JavaScript objects.

You may wish to consult on-line and textual sources for further details of each JavaScript object.

The 'global' object

When the JavaScript interpreter starts up, there is always a single global object instance created. All other objects are properties of this object. Also, all variables and functions are properties of this global object.

For client-side JavaScript, this object is the instance window of the constructor Window.

The Window object for client-side JavaScript: window

When an HTML document is loaded into a browser, a single Window object instance, named window, is created. All other objects are properties of this window object.

Since everything is a property of the window object, there is a relaxation of the dot notation when referring to properties. Thus each reference to a variable, function or object is not required to start with "window." — although this would be a more "accurate" notation to use, it is far less convenient.

Thus instead of writing:

    document.write( "Hello" );

We could write:

    window.document.write( "Hello" );

and so on.

One of the properties of the window object is the status property. This property is a String value that is displayed in the browser window's status bar. You can change the status bar with, or without, an explicit reference to the window object. Both these lines have the same effect:

    window.status = "this is a test";
    status = "this is a test";
	

The Document object: document

When an HTML document is loaded into a frame of a browser window, a Document object instance — named document — is created for that frame. This document object, like most objects, has a collection of properties and methods. Perhaps the most frequently used method of the document object is the write() method:

    document.write( "sorry, that item is out of stock<p>" );
	

One useful property of the document object is the forms property. This is actually an array of Form objects with an element for each form defined in the document. So we could refer to the first form defined in the document as follows:

    document.forms[0]

The 'call' object

When a function (or method) is executed, a temporary object is created that exists for as long as the function is executing. This object is called the call object, and the arguments and local variables and functions are properties of this object.

It is through use of this call object that functions/methods are able to use local argument and variable/function names that are the same as global variables/functions, without confusion. The call object is JavaScript's implementation of the concepts of variable/function scoping — i.e. determining which piece of memory is referred to by the name of a variable or function, when there are global and local properties with the same name.

String objects

Strings are objects. A frequently used property of String is length. String includes methods to return a new String containing the same text but in upper or lower case. So we could create an upper case version of the String "hello" as follows:

        var name = "hello";
        alert( name.toUpperCase() );
	

It should be noted that none methods belonging to string objects never change the string's value, but they may return a new String object, such as in the example above.

Array objects

Since Arrays are rather an important topic in the own right, Array objects are given their own section at the end of this unit — although you may wish to skip ahead to read that section now to help your understanding of object with this more familiar example.

Function objects

You should refer back to the earlier unit on functions.

As previously stated, functions are of the type Function, and can be treated as data variables or properties, or they can be treated as sub-programmes and executed using the () operator.

Math objects

The Math object provides a number of useful methods and properties for mathematical processing.

For example, Math provides the following property:

Math.PI

that is useful for many geometric calculations.

An example of some other methods provided by the Math object include:

    Math.abs();
    Math.round();
    Math.max( n1, n2 );
	

These may be used in the following way:

    document.write( "<p>PI is " + Math.PI );

    document.write( "<p>The signless magnitudes of the numbers -17 and 7 are "
         + Math.abs( -17 ) + " and " + Math.abs( 7 ) );

    document.write( "<p>The interger part of 4.25 is " + Math.round( 4.25) );

    document.write( "<p>The larger of 17 and 19 is " + Math.max(17, 19) );
	

The 'Triangle' object

To focus our investigation of user defined constructors and objects, we will create 'Triangle' objects. We shall be defining the Triangle constructor function as follows:

  • Constructor Function - Triangle( initWidth, initHeight)

  • Properties - numSides, width, height, colour

  • Methods - larger( t1, t2), area()

As you work through this section on JavaScript objects you will become familiar with not only with Triangle objects, but with the definition and use of your own constructors and objects.

The following is an example of some code using Triangles:

    var triangle1 = new Triangle(10, 20);

    document.write("<p><b>triangle1 has height: </b>" +
    triangle1.height );
    document.write("<p><b>triangle1 has width: </b>" +
    triangle1.width );
    document.write("<p><b>triangle1 has area: </b>" +
    triangle1.area() );
    document.write("<p><b>triangle1 has colour: </b>" + triangle1.colour );
      

The browser output from the above code is:

User defined objects

Constructor functions

Objects are created with the new operator and a constructor function. The new operator requires the name of a function to its right (with optional arguments), and will return a reference to the memory location of the newly created object.

Examples of creating objects include:

    var myArray1 = new Array( 3 );
    var myArray2 = new Array();
    var fistName = new String( "Jonathan" );
    var catPicture = new Image();
 

If we assume we have a defined a Triangle constructor, we can create new objects in just the same way as above:

    var triangle1 = new Triangle( 5, 10 );
    var triangle2 = new Triangle( 10, 20 );
    var triArray = new Array( 3 );

    triArray[0] = new Triangle( 17, 92 );
 

A constructor function creates a new object, possibly initialising some of these new objects properties based on arguments provided when the function was called. We can see from the above that the Array() constructor function can create an array if provided with no arguments, or a numeric argument (for the size of the array), or a number of arguments (for the initial elements of the array).

Our Triangle constructor requires two arguments — the first is the width of the new triangle, the second is the height. Our Triangle constructor function looks as follows:

        function Triangle( newWidth, newHeight )

        {
        this.width = newWidth;
        this.height = newHeight;
        }
 

Constructor functions make use of the special variable this — when a function is called with the new operator, a new object is created in memory, which the this variable refers to. Using this variable, the constructor is able to assign values to new properties called width and height. When a constructor function finishes, the reference to the newly created object is returned.

So after the following line is executed:

        var triangle1 = new Triangle( 5, 10 );
	

the object triangle1 should have a width property with value 5 and a height property with value 10.

This can be investigated by using the dot notation and some document.write() statements:

        document.write("<p> width is : " + triangle1.width );
        document.write("<p> height is : " + triangle1.height );
 

resulting the following browser output:

We can imagine memory to be arranged something like the following (remember that all object variables are reference variables):

Functions are objects with properties

Now we have a constructor function, Triangle, we can use this function object as an object that defines Triangles.

Object 'prototypes'

A constructor function object has a has a special property named 'prototype' — this is an object through which inheritance is implemented for all objects created from the constructor: every object created from the constructor can inherit the properties and methods of the prototype object.

For example, by creating a new property or method for the prototype, this property or method is made available to all objects created from the constructor. Prototypes are a very useful way of defining methods for objects, and for setting default object properties.

For example, let us imagine that we wish all our Triangle objects to have the property colour initially set to the String "blue". To provide this property to all Triangle objects created in the future, we can assign the property to the Triangle prototype as follows:

        Triangle.prototype.colour = "blue";
 

Likewise, if we wish to make a method available to all Triangle objects, we need to assign a function to an appropriate property of the prototype. As useful method for Triangle objects is the calculation of their area. A function to calculate the area of a triangle could be defined as follows:

        function triangleArea()
        {

        // triangle height is half (width * height)
        var area = 0.5 * this.height * this.width;

        // return calculation to 2 decimal places
        return Math.round( area * 100) / 100;
        }
 

Notice how this function has been written to refer to whatever object it is called from by using the variable this.

We now need to assign this function to a property of the Triangle prototype. The method name area seems a good choice:

        Triangle.prototype.area = triangleArea;
 

Notice, we are not executing this function, so we do not use the () operator. We are making Triangle.area refer to the same Function object as triangleArea.

After adding the above lines to a script, we can now see if a newly created Triangle object has a colour property and can use its area method:

        var triangle1 = new Triangle( 5, 10 );

        document.write("<p> colour property is: " + triangle1.colour);

        document.write("<p> area method returns: "+ triangle1.area() );
	

Remember, to invoke a function/method we must follow the function name with the () operator as above.

Implementing instance variables and methods

There is a distinction made to where variables and methods belong:

  • instance variables — these are properties that can be different for each instance object (e.g. triangle1 might have height 25, while triangle2 has height 40).

  • instance methods — methods that each object can apply to itself, and that has access to the properties of the object (e.g. triangle1 can call its area method, this method returns a value calculated using the height and width properties of variable1).

  • class variables — in a class-based object model, these are variables useful / relevant to the class as a whole, but that do not have anything to do with any particular instance of the class (e.g. the number of sides of a Triangle is 3, the value of PI is 3.1415926535). JavaScript, too, has the concept of "class variables", but the variables do not belong to classes, but rather to the constructor functions (which themselves are Function objects). These kinds of variables do no require an instance created from the Triangle or Math constructors in order for them to have meaning.

  • class methods — Similar to class variables, these are methods that are useful / relevant to the constructor function, and does not require an instance of any object created by the constructor in order for it to be useful.

We shall briefly consider how each of these is implemented in JavaScript.

Instance properties and instance methods

The previous section on the prototype property illustrates precisely what is meant by instance properties (properties) and instance methods:

  • A property added to the prototype, or created inside the constructor, is an instance variable (property).

  • A method added to the prototype (or in the constructor) is an instance method.

In fact, since a method is just a special kind of property, instance variables and instance methods can all be considered to be implemented as instance properties of the prototype.

You may find it useful to clearly comment the implementation of instance properties and methods in your code, such as the following lines illustrate:

        //////////////////////////////////////////////
        // instance (object) methods
        //////////////////////////////////////////////

        function triangleArea()
        {

        // triangle height is half (width * height)
        var area = 0.5 * this.height * this.width;

        // return calculation to 2 decimal places
        return Math.round( area * 100) / 100;
        }

        // add instance method "area" to the "prototype" property of  "Triangle"
        // (i.e. add this method to the "prototype" property of the "Triangle" constructor function object)

        Triangle.prototype.area = triangleArea;

        //////////////////////////////////////////////
        // instance (object) variables (properties)
        //////////////////////////////////////////////
        // the default colour for triangles is "blue"

        Triangle.prototype.colour = "blue";
 

Class properties

A "class properties" can be implemented by assigning a value to a property of the constructor object. This has been done for values such as Math.PI.

For example, we can implement the class property numSides with a value of 3 to the Triangle constructor as follows:

        //////////////////////////////////////////////
        // class properties
        //////////////////////////////////////////////
        // add property "numSides" 

        Triangle.numSides = 3;
	

At any later point in the code we can then refer to this class property using the dot notation. For example:

    document.write( "the number of sides of a triangle is: " + Triangle.numSides );
 

Class properties can be referred to even if no instances have been constructed (since the property belongs to the constructor, and not to the prototype).

Class methods

A class method, such as Math.abs(), is implemented in the same way as a class property — a function is assigned to a property of the constructor function.

For example, we can we can implement a Triangle class method called larger(). This method requires two arguments, each a Triangle object, and returns the String "first" if the first Triangle is the larger, otherwise the method returns "second" (i.e. if the second is the same or larger it returns "second"). First we must create a function:

        function triangleLarger(t1, t2)
        {

        if( t1.area > t2.area )
        return "first";
        else
        return "second";

        }
	

t1 and t2 are the two Triangle object references passed as arguments. This function makes use of the area instance method for each of the two Triangle objects — the larger triangle is defined to be the one with the larger area.

Then we must assign this function to an appropriately named property of the constructor object:

        // add function to constructor (i.e. add to constructor function object)

        Triangle.larger = triangleLarger;
	

Notice, we are not executing this function, so we do not use the () operator. We are making Triangle.larger refer to the same Function object as triangleLarger.

The method can the be used as follows:

        var triangle1 = new Triangle(10, 20);
        var triangle2 = new Triangle(5, 10);

        document.write("<p><b>the larger of triangles 'triangle1' and 'triangle2' is the </b>");
        document.write( Triangle.larger( triangle1, triangle2 ) );
 

The browser output for the above code is as follows:

The JavaScript object search chain

When an object is created, a reference is created to the location in memory where the object's properties and methods are stored. Also, a reference is created to the object's prototype. When JavaScript wishes to retrieve the value of one of this object's properties, or to invoke one of this object's methods, it will first search the details stored for the object, and then if the desired property/object is not found it follows the reference to the object's prototype, where it continues to search there for the property or method. Again, if the property/method is not found in the prototype, it searches the prototype object's own prototype, and so on. Eventually, if not found, JavaScript will reach the object Object — this is the 'parent' of all built-in and user-defined objects.

If the property or method is not found, the value undefined is returned.

It is important to bear in mind that objects are reference types, as are prototype objects (since they are themselves only objects).

Overriding inheritance

In the previous sections we have investigated the JavaScript features of prototypes and object inheritance. However, any object can override an inherited property or method by defining its own.

In our Triangle example, we have created a prototype colour property with a value of the String "blue". This means that, by default, all our Triangle objects will inherit this property and value. However, let us consider that while for most objects the colour blue is fine, for the object triangleR we may wish to have a colour property with value "red". The programming of this situation is very straightforward:

        var t1 = new Triangle( 10, 20 );
        var triangleR = new Triangle( 6, 6 );
        triangleR.colour = "red";
	

After execution of the above lines, part of the memory will look as follows:

When JavaScript comes across code referring to the colour property of object triangleR:

        document.write( "colour of triangleR is " + triangleR.colour );
	

it will follow the reference for triangleR to location 001741 and search for a property colour. It will succeed at location 001743. The value of this property will be returned, and this value, "red", will be passed to the document.write() method. Since the property value was found at the object referred to by traingleR, no search is made of the Triangle object prototype. In this way, object triangleR has been said to have overridden the inherited colour property with its own value of "red".

It is important to notice that although the object referred to by triangleR has overridden its inherited colour property, there has been no change to any of the other Triangle objects. So, for example, object t1 still inherits the colour property of Triangle.prototype.

Note - the difference between JavaScript and other object-language

In JavaScript, a specific object can override what it inherits from its object prototype. All other objects inheriting from the prototype can remain unaffected by this change. This differs from many other languages, such as Java, where any changes in inheritance are reflected across all objects of that given type.

The dynamic nature of inheritance through prototype references

A final concept to appreciate regarding prototype based inheritance in JavaScript is that the inheritance of prototype properties and methods is dynamic: if an object is created and the prototype is subsequently changed, the changes will be reflected in the state and behaviour of any object inheriting from it.

We shall illustrate this dynamic inheritance with the following code:

        var myTriangle = new Triangle( 6, 8 );
        var triangle2 = new Triangle( 11, 22 );

        document.write("<p> colour of myTriangle is " + myTriangle.colour );
        document.write("<p> colour of triangle2 is " + triangle2.colour );

        Triangle.prototype.colour = "green";

        document.write("<p> colour of myTriangle is " + myTriangle.colour );
        document.write("<p> colour of triangle2 is " + triangle2.colour );
 

The browser output from this code is:

After the execution of the first two lines:

        var myTriangle = new Triangle( 6, 8 );
        var triangle2 = new Triangle( 11, 22 );
 

part of the memory will look as follows:

So when the first two documemt.write( ) statements are executed:

        document.write("<p> colour of myTriangle is " + myTriangle.colour );
        document.write("<p> colour of triangle2 is " + triangle2.colour );
	

JavaScript retrieves the inherited colour "blue" for each object.

However, after execution of the line that changes the prototype property:

        Triangle.prototype.colour = "green";
	

memory is changed to look as follows:

Thus when the last two documemt.write() statements are executed, the reference is followed to the colour value at location 001734 "green", and it is this changed property value that is inherited by both the Triangle objects.

It is important to understand, then, that changing a prototype dynamically changes the inherited properties and methods for all objects sharing the prototype from that point onwards, and should not be an action used lightly, or when some simpler solution is possible.

Object activities

Activity 4 - Iterating through object properties

Create an object customer1 with the following properties and values:

Write a for/in loop that will iterate through the properties of this object, displaying each property name and value a separate line.

The browser output should look something like the following:

You can find a discussion of this activity at the end of the unit.

Activity 5 — Constructor function for Rectangle

Create a constructor function for Rectangle objects. The properties of new Rectangle objects to be initialised in the constructor are its length and height.

Your constructor function should be designed to create new Rectangle objects with code such as the following (note the length is the first argument, and the height the second):

    var rect1 = new Rectangle( 15, 20 );
    document.write("<p> length is : " + rect1.length );
    document.write("<p> height is : " + rect1.height );
 

The output of such code should be as follows:

You can find a discussion of this activity at the end of the unit.