|Monday, 18 October 2010|
Page 1 of 3
Prototype as inheritance
The key idea to using the prototype mechanism as a way to build an inheritance chain is to realise that you don't simply have to add single properties and methods to it.
Why not set the prototype property to a complete new custom object?
In this case the object created by the constructor would essentially "inherit" all of the methods and properties defined in the object used as the prototype.
This is the sense in which the prototype mechanism is all about inheritance.
Let's look at a simple example. Suppose we have a constructor for a 2D point object:
Notice that this has two properties, x and y, and a single method to set the properties.
Now we can use this as the base constructor for a 3D point object's constructor:
This creates an object with a single property of its own that is z but by setting its prototype property to a new instance of Point2D it also has x,y and the setPoint method supplied by the Point2D object.
If you try:
var Points=new Array(10);
you will discover that both the x and z properties work as you would expect. Notice that a single copy of the setPoint method is used by all of the instances of Point3D. Also notice that each Point3D object acquires its own personal x and y properties as soon as the setPoint method is called to set them to particular values.
So at the end of the for loop Point3D has three locally implemented properties x, y and z.
That is the prototype object supplies its methods and initially its properties to the receiving object but as the receiving object uses the properties it makes local versions of them.
This is a dynamic language and this is how it should behave.
It is clear that the setPoint method that Point3D inherits really isn't good enough - it only sets two of the three co-ordinates. In many cases you need to override an inherited function to change the way it works. To a certain extent this is a traditional static class based way of thinking of the problem.
What this means is that to override a method inherited from the prototype object you simply redefine it. This looks a lot like what happens in a class based language but notice that the new function simply has to have the same name and not the same number of parameters.
For example if you write:
then there is no way you can access the original inherited setPoint function only the new three parameter version. Of course in this case just making the z parameter optional would recover the same functionality but this isn't usually the case.
If you really need access to the base object's function then you have to store a reference to the prototype object in a suitably named property.
With this definition
calls the new Point3D method and
calls the original Point2D method. Of course you could simply use
to call the base method without having to modify the 3D object.
|Last Updated ( Monday, 18 October 2010 )|