Search code examples
javascriptconstructorprototypejsprototype

What is the point of prototypes in JavaScript? Why not add method directly to constructor?


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.


Solution

  • 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.