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

So, I am going through several JavaScript lessons in CodeAcademy, and I came across this section regarding prototypes.

A bit from the code:

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

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

I do not understand how this is done. Why not just do it? (As I first found out.)

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

The second way: all together in one block and not divided. What is the advantage of the first? I know what it is, I just don’t see it.

+4
source share
2 answers

, , . this. .

, .

+2

. . , .

0

All Articles