3

Im curently learning about the prototype. Is it better to put the function "sayName" in the class or add it later via a prototype? or is it the same and depends on the situation?

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

    };
}


var penguin = new Animal("Captain Cook", 2);
penguin.sayName();

or

function Animal(name,numLegs){
    this.name = name;
    this.numLegs = numLegs;
}

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


var penguin = new Animal("Captain Cook", 2);
penguin.sayName();
Hello-World
  • 9,277
  • 23
  • 88
  • 154
  • possible duplicate of [Overriding methods in Javascript](http://stackoverflow.com/questions/15497259/overriding-methods-in-javascript) – Aadit M Shah Apr 04 '13 at 08:26
  • See my **comments** on these answers: https://stackoverflow.com/a/71923547/1599699 https://stackoverflow.com/a/62142995/1599699 – Andrew Feb 05 '23 at 01:05

3 Answers3

3

It's not the same, as the first version will use more memory, as ever instance of Animal has its own this.sayName. In the latter, all Animal instances have access on the same sayName:

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

var dog = new Animal(4, "Jack");
var alligator = new Animal(4, "Snap");

dog.sayName = function(){ console.log("woof"); }

dog.sayName();
alligator.sayName();

Will result in

woof
Hi my name is Snap

because dog and alligator don't share same the function sayName, whereas a change to the prototype in your latter example would change all calls of sayName.

Zeta
  • 103,620
  • 13
  • 194
  • 236
1

It is better to use prototype for shared resources

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • A pitfall would be if you use plain objects in the prototype – they can surprisingly be mutated from one instance to another. – David Hellsing Apr 04 '13 at 08:33
1

This question has already been answered - it depends upon the situation. Read this answer: https://stackoverflow.com/a/15497685/783743

If your method needs to access private variables of the constructor then you have no option other than to define it inside the constructor. Otherwise you should always declare them on the prototype object.

You should also read the following articles:

  1. http://javascript.crockford.com/private.html
  2. https://stackoverflow.com/a/8096017/783743
Community
  • 1
  • 1
Aadit M Shah
  • 72,912
  • 30
  • 168
  • 299