top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What is prototype in javascript? What does it do?

+2 votes
431 views
What is prototype in javascript? What does it do?
posted Jun 24, 2014 by Vrije Mani Upadhyay

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

Prototype allow to declare method for objects that will be shared between each instance of the objects
Lets take this code

var myObj = function() {};

myObj.prototype.test = function() {
  alert('test');
};

You will call it with
var instance = new myObj();
instance.test();
So test() is now a method of myObj
But since you declared it with prototype, even if you create 100 myObj, the test function will simply be 1 time in memory.

So if we didn't use prototype like so

var myObj = function() {};

myObj.test = function() {
  alert('test');
};

And create 100 new myObj, in memory you will have 100 time the test function

So most of the time (99% of the time) you will want to declare your method as prototype

answer Jun 25, 2014 by Devyani
...