In the following example, the Bird constructor defines two properties: name and numLegs:
function Bird(name) {
this.name = name;
this.numLegs = 2;
}
let duck = new Bird("Donald");
let canary = new Bird("Tweety");
name and numLegs are called own properties, because they are defined directly on the instance object. That means that duck and canary each has its own separate copy of these properties. In fact every instance of Bird will have its own copy of these properties.
Since numLegs will probably have the same value for all instances of Bird, you essentially have a duplicated variable numLegs inside each Bird 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 the prototype of Bird. Properties in the prototype are shared among ALL instances of Bird. Here's how to add numLegs to the Bird prototype:
Bird.prototype.numLegs = 2;
Now all instances of Bird have the numLegs property.
console.log(duck.numLegs);
console.log(canary.numLegs);
My Question: "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."
What is the issue with having duplicated variables? Is it that they take up memory? And does it slow your program down?
Thanks in advance :)