Hi. I have a question about this exercise. I have found that it works with two different ways:
#1
function Dog(name) {
this.name = name;
}
Dog.prototype.numLegs = 4
// Only change code above this line
let beagle = new Dog("Snoopy");
#2
function Dog(name) {
this.name = name;
Dog.prototype.numLegs = 4
}
// Only change code above this line
let beagle = new Dog("Snoopy");
It works with the “Dog.prototype.numLegs = 4” assigment, both inside or outside the function. I would like to know if there is any important concept about this difference.
Your version #1 is the better of the two options for at least three reasons, likely in this order from most important to least:
The Dog constructor has one job – to create an instance of Dog. In version #1, it does exactly that. In version #2, it does that plus setting an attribute of all Dog instances. In this particular case, the code is simple enough that it is still easy to read/understand. In larger codebases, having functions that do multiple things at once – particularly when what they do could affect other objects – gets confusing very quickly.
In this example, it’s pretty unlikely that you’ll want to change the value of numLegs while the program is running. But in more complex programs, you may want the prototype to reflect a value that could be provided by the user. In version #1, that would be easy! Just change Dog.prototype.numLegs once to the new value. But in version #2, if you change the value, every time you create a new instance of Dog it will set it back to 4.
In version #2, you are setting numLegs to the same value every time you run Dog. This is not a computationally expensive operation, but you might as well save the processing time/power – much more efficient to just do it once like in version #1