Using prototype to add methods to classes?


#1


I'm trying to wrap my head on how prototypes work. Is using prototype just another way to add a method to a class? Does the method for bark in the code below work exactly the same?


//1
Dog.prototype.bark = function () {
    console.log("Woof!");
}

//2
function Dog (name) {
   this.name = name;
   this.bark = function () {
       console.log("Woof!");
   };
}

Is there a difference in the methods in each code?
Is there a benefit doing it one way or another?
Using prototype looks like extra work in creating more lines of code when it could just be written within the object constructor.


#2

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.