DEV Community

Randy Rivera
Randy Rivera

Posted on

Using Prototype Properties to Reduce Duplicate Code

  • Continued.
  • Since numLegs will probably have the same value for all instances of Dog, you essentially have a duplicated variable numLegs inside each Dog instance.
  • This may not be an issue when there are only two instances, but imagine if there are millions of instances. That would be a lot of duplicated variables.
  • A better way is to use Dog’s prototype. Properties in the prototype are shared among ALL instances of Dog. Here's how to add numLegs to the Dog prototype:
Dog.prototype.numLegs = 4;
Enter fullscreen mode Exit fullscreen mode
function Dog(name) {
  this.name = name;
}

Dog.prototype.numLegs = 4;

let beagle = new Dog("Snoopy");
let husky = new Dog("Rex";
Enter fullscreen mode Exit fullscreen mode
* Now all instances of `Dog` have the `numLegs` property.
Enter fullscreen mode Exit fullscreen mode
console.log(beagle.numLegs); // will display 4
console.log(husky.numLegs); // will display 4
Enter fullscreen mode Exit fullscreen mode
  • Since all instances automatically have the properties on the prototype, think of a prototype as a "recipe" for creating objects. Note that the prototype for beagle and husky is part of the Dog constructor as Dog.prototype. Nearly every object in JavaScript has a prototype property which is part of the constructor function that created it.

Top comments (0)