Marching Penguins


#1

It might be that we are learning about prototype but what would be the purpose of it if we just write the property inside the object like so,

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

var theCaptain = new Penguin("Captain Cook", 2);
theCaptain.sayName();

it still prints out the same result
//Hi my name is Captain Cook

as,

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

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

var theCaptain = new Penguin("Captain Cook", 2);
theCaptain.sayName();

#2

Using prototype, you can modify Objects that you aren't the creator of.

e.g. String


#3

would you only use this method in a way of debugging? is it best real-world practice not to modify someone's code?


#4

Instead of attempting to explain the usage of prototype to you (which I would surely fail at), take a gander here.


#5

Prototypes are portable and dynamic. They can be modified on the fly and every member inheriting from it has immediate access to the modified methods/objects, whether instanced before or after the change. Changes in a constructor are only reflected in new instances following, not previous to the change.

By changes I do not mean physical edits, but toggling or case selecting functions to assign to a pointer under various states. It's possible to have several versions of a class all with variants in their direct properties. Their constructor's prototype is what they inherit from, though. This is where to extend the attributes and methods that are available to all of the class, or sub-class.