Javascript Jems - The Prototype |
Written by Ian Elliot | |||||||||||||
Monday, 04 October 2010 | |||||||||||||
Page 3 of 3
Dynamic objectsJavascript objects are dynamic and assigning to a property that doesn't exist is another way of creating it. So after the assignment Points[i] has its very own z property and no longer makes use of the prototype mechanism to fill in for a property it doesn't have. You can see that providing a prototype property is a storage saver initially at least. It provides default values for all of the properties that an object gets via the prototype mechanism without allocating any additional storage. As the objects make use of the properties to store unique values then the additional storage is allocated - its a neat mechanism once you understand it. Of course the prototype mechanism works in exactly the same way for properties and methods - the only difference is that you usually don't assign a new "value" to an inherited method. As we shall see in the next article however redefining a method that has been supplied as a prototype is one of the core things that you do if you start to use its as a way of implementing inheritance. The Javascript wayThus the constructor's prototype property and the associated mechanism that Javascript uses to properties and methods undefined in the object instance allows the constructor to act as a central repository of methods and to a lesser extend properties for all of the instances created by the constructor. Now you can see that it's not so difficult and once you follow the connection between the constructor and the objects it creates it is even very logical. However you need to keep in mind that Javascript is not a classical class based object oriented language and there are advantages in not hobbling it with concepts that don't really suit it. In the next article we will take a closer look at how the prototype mechanism can be treated as if it was classical inheritance and see how to build up inheritance hierarchies. However as you might expect Javascript being a dynamic language doesn't quite play by the rule that you might expect.
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.
<ASIN:059680279X> <ASIN:1430230541> |
|||||||||||||
Last Updated ( Monday, 18 October 2010 ) |