by Dinesh Thakur Category: Javascript String

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:


   <script type="text/JavaScript">
    var rightnow= new String("Joe");
    document.write("This string is "+rightnow.attitude);

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.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");
About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.

Search Content