In this tutorial i am going to show you how to use prototype object in javascript to change the way you used to code. Prototype is an amazing way to add custom properties/methods to your existing legacy Objects or make your own. Well did that sound complicated ? Hmmm.. Lets go further and make sense. Basically protoype starts just when you say, OMG i wish javascript could support objects and i shall be able to do this and that..

We are already using objects in javascript, as a matter of fact some of us just don’t realize it. Now if i wish to create a new window and open it from here what would it do ?

function createWin()
var doc=newwin.document;
doc.title="Created a new window |";
<input type="button" value="Create a new window" onclick="createWin();" />

So if you see in the above example i have just played around with the window and document object. You can manipulate the object and its properties the way you want to.Change title append more elements into body and way more than that.

So that is how we work with standard elements in javascript. We can create our own custom elements and can associate objects with it and then certainly properties and methods. These standard elements can be hooked with our own custom properties and methods to make the javascript more powerful. Like you can associate custom trim function with String which is not present in javascript by default. I will show you how you can achieve this in the next tutorial. But for now lets concentrate on what prototype is and how easily can we implement / use in javascript.

This also lets you create a namespace like thing in javascript. So if you have multiple functions with same name, then no problem cause that is where namespace comes handy 🙂

Now let me show you how can we achieve the above discussed.

We have this in our realin.js

function realin()
    alert("this is my function with an argument "+var1);
    alert("This value got assigned from outside "+this.in1);
    alert("well i am display function can be called using \"this\" keyword");

realin.js is included in html and can be used in any html(test.html)

<script src="realin.js" language="javascript"></script>
    var realin=new realin();
    realin.myfunction("my variable"); //calls the first function
    realin.myfunction2("outside"); //it assigns a value to a variable inside the protoype
    realin.display(); //simple display function can be called from outside or inside the JS file
<input type="button" onclick="test();" value="click">

We have created an object called realin for the function realin, you can have as many objects you want to and you can name them whatever you want to. And then you can properties and methods from the function using your object. Like this way i showed in above code.

I hope that works for you. Any problems, leave a comment !!

Cheers !!
Realin !

Share this post: