Are these the same?


#1


https://www.codecademy.com/en/courses/objects-ii/3/2?curriculum_id=506324b3a7dffd00020bf661


Hello!

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


//This:

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

//...and this:

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


#2

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.


#3

A lot clearer now! Thank you!


#4

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.


#5

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