Why use prototypes? 16.It's all in the Genes


#1

Hi all,

I wondered why or when prototypes become important?
I find it much more effective to implement the (lets say) wanted function into the constructor.
Take this code as an example:
// create your Animal class here
var Animal = function(name, numLegs) {
this.name = name;
this.numLegs = numLegs;
this.sayName = function() {
console.log("Hi my name is " + name);
}
};

// create the sayName method for Animal

// provided code to test above constructor and method
var penguin = new Animal("Captain Cook", 2);
penguin.sayName();

We completely skipped to write the prototype function and instead implemented it into the constructor itself.
If someone could elaborate on this I would be pleased.

CODE DOES NOT WORK TO SOLVE THE TASK;
IF YOU ARE STUCK ON THE TASK HERE IS THE CORRECT CODE:

// create your Animal class here
var Animal = function(name, numLegs) {
this.name = name;
this.numLegs = numLegs;
};

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

// provided code to test above constructor and method
var penguin = new Animal("Captain Cook", 2);
penguin.sayName();


#2

@wilhelminapepermunt,
Please read
https://www.codecademy.com/forum_questions/55a1ff5b9113cb0df10005f4#comment-55a3119e937676536e0005ea
to get a better feel on "Javascript Prototype Chaining"


#3

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