The Array object has a prototype Array.prototype and the object instance, num, inherits the properties of the Array object.
This is why you can use a method like sort() on an array instance.
Same thing goes for other objects like
When a constructor (a.k.a. pseudo classical inheritance) function is built, the newly created objects inherit the prototype properties of the constructor function and that’s the critical feature of constructors. They (constructor functions) are built for the initialization of newly created objects. Constructors are invoked using the new keyword.
From the example above, the carDate, getColor and getModel functions are properties of the Car object and instances of the Car object like firstCar can inherit all its properties.
When an object gets a request for a property that it does not have, its prototype will be searched for the property, then the prototype’s prototype, and so on. So who is the prototype of an object? It is the great ancestral prototype, the entity behind almost all objects, Object.prototype. Many objects don’t directly have Object.prototype as their prototype, but instead have another object that provides a different set of default properties. Functions derive from Function.prototype, and arrays derive from Array.prototype and so on.
The protoRabbit acts as a container for the properties that are shared by all rabbits. An individual rabbit object, like the killerRabbit, contains properties that apply only to itself — in this case its type — and derives shared properties from its prototype.
Let’s look at this code:
But, if bar weren’t found on myObject , its prototype chain, if nonempty, is again consulted and followed. This process continues until either a matching property name is found, or the prototype chain ends. If no matching property is ever found by the end of the chain, the return result from the operation is undefined.
Similar to this prototype chain lookup process, if you use a for..in loop to iterate over an object, any property that can be reached via its chain and is also enumerable will be enumerated. If you use the in operator to test for the existence of a property on an object, it will check the entire chain of the object (regardless of enumerability).
The method speak in the code above is in efficient because if you were to create multiple rabbit objects, you would have the same function written everywhere and that’s where prototype and constructor functions really come in. It can be re written like this: