17. Marching Penguins why can't I do it this way?


#1

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

// create a Penguin constructor here
function Penguin(name, numLegs) {
this.name = name;
this.numLegs = numLegs;
this.sayName = function() {
console.log("Hi my name is " + this.name);
}
}
// create a sayName method for Penguins here

// our test code
var theCaptain = new Penguin("Captain Cook", 2);
theCaptain.sayName();`

Okay, I guess they want me to do Penguin.prototype.sayName...but why? Isn't my code the same thing, giving every instance of Penguin the sayName method? What am I missing?


#2

When a property is a fixed value or method that needs protection, we use var in the constructor to define these class variables. They are constant in every instance. When a property is scoped to an instance, so that each instance has its own value, then this is the variable in every instance, and is tied to the owner object. But we needn't have methods with this in their identifierName.

When we write a custom prototype, there is only one reference to it. When we write methods in constructors we create multiple instances of what is essentially the same piece of code that only needs a single reference; ergo, the prototype extension.

One thing that writing methods to the custom prototype avoids is the occurance of unknown properties in older written object instances. If we only change the constructor in future, it will not take into account earlier created objects in a data base. Only new objects after the change will reflect the change. By writing to the prototype, all it takes is one update cycle and an entire data base can be revised. Older objects (of the class) get the new properties since they all inherit from the same prototype.

This will take more reading. Lots more reading. Please don't cheat yourself of this. Get out there and do it.