java

java

In my last article I discussed the ways of defining objects and creating new ones. Our discussion was restricted to defining objects that didn’t have functions / methods. In this article, we will see how we can define methods for an object, as well as ways of extending the functionality of an object.

Defining A Method

A method is a function / service that an object is capable of carrying out. This may result in reading, displaying or changing some or all of the properties of that particular object. The execution of a method doesn’t change / effect the properties of other objects. For example, a door is capable of performing services like “open” or “shut“. But carrying out one of these services never results in changing the status of other doors.

We will study the example of a class “Door” defined as below:

function Door (status)
{
this.status = status;
}

Next we can create several doors as doorA = new Door (“open”); or doorB = new Door (“close”);. We can also read the values of the “status” property as alert(doorA.status). The services that a door performs can be written in JavaScript as:

function close()
{
this.status = “close”;
}
function open()
{
this.status = “open”;
}

Calling these methods will only change the status property of the door for which they are called. But first we must connect the definitions of these methods with the definition of the “Door“.

Adding Methods to an Object

Once the functions are written we can add them to an object by using the following syntax. Note that “Door” is the name of the class; prototype is a built-in property of all objects while close and open are the methods that we want to add. The names close and open at the right hand side of the equal to sign are of the methods that we defined above.

Door.prototype.close = close;
Door.prototype.open = open;

Once this is done we can easily change the status of a door by calling it like doorA.close() or doorA.open(). Using these techniques we can also add methods to existing built-in objects like String and Math.

A Complete Example

The following example is an extension to the class defined in my last article. Everything is self explanatory, but you should ask questions in the discussion area, if you don’t understand something.

<html>
<head>



</head>
<body onLoad="start()">
</body>
</html>

The following steps are required to define and add methods to an object:

  1. First define an object.
  2. Write the function. Give it any name. You can access the properties of the object (where you will add this function) by using this.
  3. Add the function to the object by using objectName.prototype.methodName = functionName.

Leave a Reply

Your email address will not be published.