Using Prototype Properties to Reduce Duplicate Code
Randy Rivera
Posted on June 9, 2021
- Continued.
- Since
numLegs
will probably have the same value for all instances ofDog
, you essentially have a duplicated variablenumLegs
inside eachDog
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 theprototype
are shared among ALL instances ofDog
. Here's how to addnumLegs
to theDog prototype
:
Dog.prototype.numLegs = 4;
function Dog(name) {
this.name = name;
}
Dog.prototype.numLegs = 4;
let beagle = new Dog("Snoopy");
let husky = new Dog("Rex";
* Now all instances of `Dog` have the `numLegs` property.
console.log(beagle.numLegs); // will display 4
console.log(husky.numLegs); // will display 4
- Since all instances automatically have the properties on the
prototype
, think of aprototype
as a "recipe" for creating objects. Note that theprototype
forbeagle
andhusky
is part of theDog
constructor asDog.prototype
. Nearly every object in JavaScript has aprototype
property which is part of the constructor function that created it.
💖 💪 🙅 🚩
Randy Rivera
Posted on June 9, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.