Categories:
Partners
Web Hosting
We've partnered with HostGator for reliable, affordable hosting starting at $3.95/mon. Use coupon code "javascriptkit25" for 25% off any package.

Using the prototype object to add custom methods to objects

The prototype object can also help you quickly add a custom method to an object that is reflected on all instances of it. To do so, simply create the object method as usual, but when attaching it to the object (you guessed it),  use "prototype" beforehand. Let's extend our circle object so it contains a default method that does something simple, like alert the value of PI:

//First, create the custom object "circle"
function circle(){
}
circle.prototype.pi=3.14159

// create the object method
function alertmessage(){
alert(this.pi)
}
circle.prototype.alertpi=alertmessage

Now, all instances of the circle object contain a alertmessage() method!

Copyright 1997-2014 JavaScript Kit. NO PART may be reproduced without author's permission.