17. Marching Penguins Question


#1

Hi, so I finished the exercise, but I wanna know:

How is this:

// create a Penguin constructor here
function Penguin(name, numLegs) {
    this.name=name;
    this.numLegs=numLegs;
    }

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

any different from this:

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

Isn't the second way shorter and better? What is the difference?

I didn't quite get the 'prototype'. In exercise descriptions, codecademy talks about 'changing' prototype? But, if the class is 'penguin', after writing penguin.prototype.something, the class still stays 'penguin', right? What is the difference between prototype and class?


#2

The difference is quite big. I prefer to assign methods to the prototype because you can easily change the behaviour of the method for all instances. Example -> https://repl.it/DJyU. This is not possible to achieve with internally defined methods.


The second difference, most important, is performance. Every method defined internally has to be recreated when the constructor is executed (when you create a new object). When you have a lot of objects that can be a reason for a crucial loss of efficiency.


#3

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