Aaaaah, prototypes... How many blog posts did you read where prototypes are listed as a must-know characteristic of the language? How many times senior developers told you about prototypal inheritance? I've spent quite some time avoiding to learn more deeply about this thing. I got tired of procrastinating, so I wrote this thing.
Simple words please... with examples?
Object.create creates a new object. It takes another object as an argument. The common way to think about what is happening is ( the classical way ) : I made a copy of this object. You fool!!
As you can see, newObject is empty. We didn't copy, we linked newObject to myObject. myObject becomes a prototype of newObject. To know what is inside the prototype of an object, you can use proto.
Up the chain... one link at a time.
Here is how your favourite language works: it tries to get the property a in the thirdLink object. Can't find it. Does it return undefined or a error? Nope, it looks in the prototype chain for a link. It finds out that secondComing is a prototype of thirdLink. It looks for a, still can't find it. It moves on to another link, called original. Finds a = 2 !!
What if I change something in the bottom of the chain?
- How will it affect the top of the chain? Such a great question.
I decide to change the value a in thirdLink directly:
This is what we call a shadowed property. The new a value shadows the other a values present in the higher prototypes.
What if I put some ice on it?
What if the property in the top link can't be overwritten?
Nothing changed because the prototype's property a is read-only.
However, if you need to change the property value anyway when it is read-only. You must use Object.defineProperty:
So, whenever you think you are changing a value in a object, you must account for the prototypes up the chain. They may have properties with the same name that can't be overwritten in a certain way.
What does it mean for functions?
In a class oriented language, you can create different instances of a class. You copy the class behavior into an object. And this is done again every time you instantiate a class.
By default, every function gets a prototype property.
Ok, so what happens if you don't copy like class-oriented languages? You create multiple objects with a [[Prototype]] link. Like so:
Now, let's now make the goodBye.prototype a prototype of hello.prototype:
Let me show you a disgusting thing I made, maybe it will be clearer:
Beautiful... Notice how the arrows go from the bottom to the top!
I see you waiting for some examples:
Oh, and don't bother giving me feedback about the schema, I already know it's gorgeous.