Hello-World
Hello-World

Reputation: 9555

the prototype - add function to a class

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();

Upvotes: 3

Views: 2763

Answers (3)

Aadit M Shah
Aadit M Shah

Reputation: 74204

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

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388316

It is better to use prototype for shared resources

Upvotes: 1

Zeta
Zeta

Reputation: 105885

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.

Upvotes: 3

Related Questions