Use Prototype Properties to Reduce Duplicate Code

Tell us what’s happening:

Your code so far


function Dog(name) {
  this.name = name;
  this.numLegs=2

}



// Add your code above this line
let beagle = new Dog("Snoopy");

Dog.numLegs()=function(){
return this.beagle;
}

console.log(beagle.numLegs);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/object-oriented-programming/use-prototype-properties-to-reduce-duplicate-code

You should only be adding text above the line.
The code you need to add can fit in one line!
You have to use prototype in your answer.

I don’t think using Prototype Properties can Reduce Duplicate Code.
At least in the challenge I cannot see any discrepancy between 2 ways to create new property

1 Like

In the following code, each time a new Dog is created, all the properties in dog are copied to the new instance object. That means there are 4 of each property created (one for each object). If a million Dog objects were created in this way, that would be a large memory resource requirement.

function Dog(name) {
  this.name = name;
  this.numLegs=4
  this.speak = function() {
    return 'Bark';
  }
}

// Add your code above this line
let beagle = new Dog("Snoopy");
let poodle= new Dog("Shadow");
let saintBernard = new Dog("Berny");
let collie = new Dog("Sadie");

Now, if you define numLegs speak as as Prototype properties of Dog, then with each new Dog instance created, there would only be one property (name) in all instances, but the two properties (numLegs and speak) would be a part of all the Dog instance objects without all the extra memory overhead.

function Dog(name) {
  // some other code can go here
}
Dog.prototype.numLegs = 4;
Dog.prototype.speak = function() {
  return 'Bark';
};
3 Likes

Here is a shorter version to show the duplication and not duplication of a property.
Duplication:
function Dog(name) {
this.name = name;
this.numLegs = 4;
}
let beagle = new Dog(“Snoopy”);
console.log(beagle); // { name: ‘Snoopy’, numLegs: 4 }
console.log(beagle.numLegs); // 4

And the non duplicated version:

function Dog(name) {
this.name = name;
}
Dog.prototype.numLegs = 4;
let beagle = new Dog(“Snoopy”);
console.log(beagle); // { name: ‘Snoopy’ }
console.log(beagle.numLegs); // 4

2 Likes