While talking about “duplicate variables” in each different instance of an object in the following challenge, it says “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
Bird . Properties in the
prototype are shared among ALL instances of
I think I understand what prototypes are, but why is it better if it’s in the prototype? Am I correct in assuming it’s because the code is not actually “duplicated” when it’s in the prototype? It’s just referencing the original?
Challenge: Use Prototype Properties to Reduce Duplicate Code
Link to the challenge:
Yes that’s it exactly. The “DRY - Don’t Repeat Yourself” principle reduces replication in your code.
Every extra character of code is another opportunity for typos!
It also helps make your code more modular. This means that when the time comes to change your code you can perform the change in a single place instead of having to chase through your whole codebase.
everytime we store a variable with a value, it takes memory space. Instead of storing in every
Bird object its number of wings(which by default is ‘2’), we can store it in the
Bird prototype, which is shared by all
Bird objects. That way, we store one value for all, instead one value for each one. By default, we want to store values in the separate objects, only if those values are unique, innate only for the specific object. For example, the ‘bird’ color, or its name.
Well, that is exactly the reason. The prototype is not “duplicated” when you create an instance. It is therefore efficient to declare it in the prototype so that all instances will reference the same method/property.
This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.