A JavaScript Prototype is an object from which other objects inherit properties. Every object has a prototype by default. An object in JavaScript is any unordered collection of key-value pairs. If it’s not a primitive (undefined, null, Boolean, number or string) its an object.
As with the other objects that have the JavaScript Prototype property, you can use it to add properties or methods to String objects on the page. The following code shows an example of JavaScript Prototype:
<html> <body> <script type="text/JavaScript"> String.prototype.attitude="cool"; var rightnow= new String("Joe"); document.write("This string is "+rightnow.attitude); </script> </body> </html>
Now the String object “Joe” has an attitude property of “cool”!
The Output of this code is: This string is cool
The JavaScript Prototype property is used when you have a class and you have already created a set of objects and later on, you need a new property in each of your objects.
Lets see an example of JavaScript Prototype property. First we create a class called karan with a property called Lname.
function Karan(Lname){ this.Lname = Lname; this.getLname=function(){return this.Lname;}; this.setLname=function(LnameArg) { this.Lname=LnameArg; }; }
Then we create a few objects of this class as follows.
var p1= new Karan("karan1"); var p2= new Karan("karan2");
Now Later on suppose you need to add a property ‘age’ for all karan’s objects. First way to modify the class and add a property called age to it. But what happen if the Karan class is declared in common file and is call by different javascript scrips. That the stage where the prototype property comes into existence.
We can add a property to all the instances of the class by writing the following lines of code.
var p1= new Karan("karan1"); var p2= new Karan("karan2"); Karan.prototype.age=29; console.log(p1.age); console.log(p2.age);