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!
|