Object Oriented Programming: Use Prototype Properties to Reduce Duplicate Code

Tell us what’s happening:
Hi.So the lesson says:

Since numLegs will probably have the same value for all instances of Bird , you essentially have a duplicated variable numLegs inside each Bird instance.

I cant understand how this variable is getting duplicated.Can someone explain me how this happens and why the prototype property is useful here?Thanks

Which lesson? do have a link to it?

1 Like

A guy on Reddit gave a very good solution for me.Here it is for anyone that may have the same question in the future.

Whenever you create a new Bird, the instance created gets 3 properties assigned to it: name, color, and numLegs. If you create another Bird, that instance will also get 3 properties assigned to it, meaning 6 properties total. Same with any other new Bird. Each instance means 3 new properties are created.

Prototypes are shared containers for objects. Each time you create a Bird instance, that instance will inherit from the shared Bird.prototype object, as will all others. If you add a single property to Bird.prototype, all Bird instances will have access to that property even though there is only one version of that property.

function Bird(name,color){
  this.name=name;
  this.color=color;
}
Bird.prototype.numLegs=2;
console.log(new Bird().numLegs); // 2
console.log(new Bird().numLegs); // 2 (same inherited 2 value)

So here, with 2 Bird instances, there are 5 properties rather than 6, 2 each of name and color, and one shared numLegs. Each new instance only adds 2 more properties to the system rather than 3 since there is only one numLegs that is shared with them all.

Generally, though, state is kept within the instances and methods are the only things shared between the prototype. While you can have properties like this on the prototype, it’s not usually done. One concern is if you have an object value shared this way and you change a property of that object, that change also gets shared between all objects which may not be the intention.

function Bird(name,color){
  this.name=name;
  this.color=color;
}
Bird.prototype.numLegs={count:2};

const dodo=new Bird();
console.log(dodo.numLegs.count); // 2

const hawk=new Bird();
console.log(hawk.numLegs.count); // 2

dodo.numLegs.count=1; // (unfortunate accident)
console.log(dodo.numLegs.count); // 1
console.log(hawk.numLegs.count); // 1 (oops!)

This does not happen if you keep all your properties to the individual instances.

function Bird(name,color){
  this.name=name;
  this.color=color;
  this.numLegs={count:2};
}

const dodo=new Bird();
console.log(dodo.numLegs.count); // 2

const hawk=new Bird();
console.log(hawk.numLegs.count); // 2

dodo.numLegs.count=1; // (unfortunate accident)
console.log(dodo.numLegs.count); // 1
console.log(hawk.numLegs.count); // 2 (safe!)
2 Likes