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;
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 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)
Subscribe
For further actions, you may consider blocking this person and/or reporting abuse
Top comments (0)