Page 3 of 3
This story has been long, hard and detailed and its why its difficult for beginners to get it right. Now we have one last but fairly obvious extension.
When you specify an object as being the prototype object that object can too take part in the prototype mechanism.
That is you can write a constructor for object A.
You can then write a constructor for object B which has its prototype property set to an instance of object A.
You can then write a constructor for object C which has its prototype property set to an instance of object B
and so on.
For example, suppose we define Point1D as:
and Point2D as:
and finally Point3D as:
Now if we create an instance of Point3D:
var point=new Point3D();
then the new object has a single property of its own - that is z but if you reference a y property the property chain is used and it is found in Point2D. If you reference a property x then this isn't found in Point2D but in Point1D.
That is a Point3D object inherits x and y from Point1D and Point 2D respectively.
point instanceof Point3D
is true and so are:
point instanceof Point2D
point instanceof Point1D
It has been a long story but now you are in a position to see everything from a great height.
- To make object creation easier we use functions as object factories to return objects.
- The new operator has four side effects:
- it automatically creates an annoymous object literal and sets the special varible this to reference it.
- It also returns this as the result of the function.
- It sets the constructor property of the object to a refernce to the function object i.e. the constructor
- It sets the internal __proto__ property of the object to the constructors prototype property.
- Changes to the properties of the prototype object effect the lookup for missing properties.
- Once set the __proto__ property cannot be changed and hence the prototype of an object cannot be chanaged.
- If an object assignes a value to a property that would otherwise be supplied by the prototype chain a local property is created and the prototype chain isn't used.
- The constructor used to create an object can be regarded as a definition of its "type".
The only time when there is a strong compulsion to use the prototype mechanims is when there are lots of objects involved and you need to implement methods more efficiently. That is methods provided by the constructor aren't shared between instances but methods provided by the prototype chain are shared - hence reducing the size of the code.
If you would like to be informed about new articles on I Programmer you can either follow us on Twitter, on Facebook , on Digg or you can subscribe to our weekly newsletter.