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.
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)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".
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;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.
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>Go To Page: 1 2