4

So I am going over a few lessons over JavaScript at CodeAcademy, and I ran into this section regarding prototypes.

A bit from the code:

function Dog(breed){
    this.breed = breed;
};

Dog.prototype.bark = function(){
    console.log("Bark!");
    };

I don't understand the point of doing it that way. Why not just do it this way? (The way I first learned.)

function Dog(breed){
    this.breed= breed;
    this.bark = function(){
        console.log("Bark!");
    };
}

The second way, everything is together in one block, and not separated. What is the advantage of the first one? I know that there is, I'm just not seeing it.

user1768884
  • 1,079
  • 1
  • 20
  • 34
  • @user1768884 : That's a very good question.There are quite a few guys here who are capable of giving amazingly detailed answers to such questions! Hoping to see an answer. – Harsha Venkataramu Dec 22 '13 at 20:38
  • For your small example it doesn't matter, and it doesn't really make sense to prototype, but imagine you had many objects to create, and you could use a common object as a template, and then prototype onto that common template, and once you change that common template, all the other objects would be automatically updated as well, then it would make more sense to you, and you'd understand why prototyping is great and can save you tons of work. – adeneo Dec 22 '13 at 20:39

2 Answers2

2

One difference is, that in the prototype case the function exists only once and changing it will change all objects using this prototype. In the this. case the function is repeated in every object.

This makes a difference both in footprint and semantics.

Martin Drautzburg
  • 5,143
  • 1
  • 27
  • 39
0

it is for performance reasons. when creating a new instance of objects and calling a native method you are eating more memory for every creation. On the other hand when using prototype it is more memory safe regardless the amount of Object created.

Yehia Awad
  • 2,898
  • 1
  • 20
  • 31