Prototype chains (aka prototype inheritance)
Prototype inheritance string can go as long as you wish. But in basically it is not the best idea to made long chains of your code can get painful to understand and preserve.
The __proto__ object
You can analysis that one object is the prototype of other by doing:
Prototype lookups are dynamic
You can tally properties to the prototype of an object at any period of time, the prototype chain lookup will find the new premises as expected.
New/updated properties are assigned to the object, not to the prototype
What happens if you modern a property that previously exists in the prototype? Let’s see:
Note that the property ‘kind’ now exists in both person and zack.
As explained before __proto__ isn’t a well-supported way of appointing prototypes to objects. So the later simplest way is using Object.create(). This is usable in ES5, but old browsers/engines can be shimmed using this es5-shim.
You can go throughout an object to Object.create to add specific properties to the new object.
Yes, the object you wish to pass is a little convoluted, but that is the way it is. See the docs here.
You can get the prototype of an object helping Object.getPrototypeOf
There is no such thing as Object.setPrototype.
Functions as constructors
‘this’ is assigned implicitly
When we do this:
Behind the set it is like doing object like this:
But keep in mind that the implicit ‘this’ is only assigned to a new object when using ‘new’. If you forget ‘new’ keyword then ‘this’ will be the global object. Of course, forgetting new is a cause of multiple bugs, so don’t forget new.
One convention that I like is taking advantage of the first letter of a function when it is intended to be used as a function constructor, so you now straightaway to you are lacking the new keyword.
The ‘function prototype’
As confusing as it can sound, this ‘prototype’ property is not the real prototype (__proto__) of the function.
This, of course, develops a lot of embarrassment as people use the term ‘prototype’ to refer to various things. I think that a good clarification is to ever refer to the major ‘prototype’ property of functions as ‘the function prototype’, never just ‘prototype’.
The ‘prototype’ property count to the object that will be used as the prototype of instances created with that function when using ‘new’. Confusing? This is easier to describe with an example: