Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

What is prototype in javascript ?what does it do ?

javascript

Best Answer Vaielab, 13 June 2014 - 09:26 PM

Prototype allow you 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 you 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

Go to the full post


This topic has been archived. This means that you cannot reply to this topic.
3 replies to this topic

#1 B13

B13

    CC Regular

  • Member
  • PipPipPip
  • 28 posts

Posted 12 June 2014 - 10:00 AM

What is prototype ? What does it do ?


:confused:


#2 BlackRabbit

BlackRabbit

    CodeCall Legend

  • Expert Member
  • PipPipPipPipPipPipPipPip
  • 3871 posts

Posted 12 June 2014 - 10:27 AM

Are you familiar with OOP?

Prototype allows to declare methods for objects.

 

Read this article for expanded information



#3 B13

B13

    CC Regular

  • Member
  • PipPipPip
  • 28 posts

Posted 13 June 2014 - 07:31 PM

Still unclear 


:confused:


#4 Vaielab

Vaielab

    Programming God

  • Expert Member
  • PipPipPipPipPipPipPip
  • 1382 posts

Posted 13 June 2014 - 09:26 PM   Best Answer

Prototype allow you 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 you 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


You can now stalk me on linkedin: http://ca.linkedin.c...elle/24/b44/88/ !





Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download