Are these the same?



Sorry, if I'm completely off target, but aren't these two pretty much the same?


function Animal(name, numLegs) { = name;
    this.numLegs = numLegs;
Animal.prototype.sayName = function() {
    console.log("Hi my name is " +;

//...and this:

function Animal(name, numLegs) { = name;
    this.numLegs = numLegs;
        console.log("Hi my name is ";


They basically work the same but declaring methods on prototype property can be more efficient especially if you have many instances of Animal object, method declared on prototype will be created once and will be shared across all instances, so when you call Animal.sayName(); firstly JavaScript engine will look at Animal object then it won't find sayName() but after that it will look at prototype object and it will find it, so prototypes save memory because they let you share methods. And if you declare method directly inside Animal object you will end up creating a lot of instances of that method. Prototype gives you performance, sharing advantage and makes your JavaScript code do less and work faster.


A lot clearer now! Thank you!


You can find a lot more information about class methods vs prototype methods advantages/disadvantages by 'googling' because that was just my quick and brief explanation at first you need to get a hand of it and later you will be able to master it quite easily.


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