javascript : prototype

Moving on with my study of javascript, the next thing is “prototype”. Before that, lets say it three times, “Everything in javascript is an Object“.

There are only 3 primitive datatypes in javascript! Though some refer as, there are 5 types, but all in all those are the only ones. These primitive data types are

string
numeric
boolean
//The other two are
null
undefined

Apart from these basic datatypes, everything else is an Object. Though there are predefined Objects in javascript with these primitive datatype names such as String,Number,Boolean,Null,Undefined respectively. Please refer this for a detailed understanding.
Well, the point here is everything is an Object in Javascript. Unlike other programming languages where a Class is needed to create an Object, Javascript comes with Objects from the beginning. The dynamic nature of the language allows us to do so many things in so many ways that there really needs an eye who can see the details, of how things are done.
We know from past tutorial that “prototype” is a property of an Object created with “new” keyword. What does this do? Well, this allows us to link Objects internally!! Lets take a pause and understand another very important lesson of javascript and object oriented programming in general.
In a Class based language(Java or Actionscript) it is thought as, “how to relate the Classes, so that something is possible?”, where in a dynamic language such as javascript, it is thought as “how to relate the Objects, so that something is possible?” Read it for a number of times so that you will get a hang of the metaphor and thought process difference, in mind.
So the point here is the same, we have to relate the Objects itself but not the Classes(Anyway, we do not have classes here in javascript but can fake them though).
Coming back to our “prototype”, its the property of an Object created through the use of “new”. This “prototype” property is also an Object in itself. To test this, let us refer our previous post, and the all in one page test. Go down to the “Understanding Javascript class.” box and click on the “what is prototype” button. The pop-up will say, its an Object. That’s good, lets move on and click on “prototype test” button, now it alerts “undefined” that means, “prototype” is an object but not yet defined! So lets define a prototype and call the same method again. First to assign an object to the “prototype” property click on “initiate with custom prototype” button. That will assign a custom object as the “prototype” property. Now click on the “prototype test” button again, and this time it will alert with some value, other than “undefined”.
Whoa!! Its that simple. Yes it is that simple and for the same reason many confuse with the concept. After all the world has become complicated to understand simple things :) :)

The source code of the example is here to download.
Happy coding.