JS Prototypal Inheritance

Early on I had a difficult time understanding Javascript inheritance (sometimes I still scratch my head), mainly I think of the fact of how it differs from the classic model. I’ve heard several different answers some short and some long mostly because of the prototypal caveats. My take is fairly straightforward (in my mind at least…). In javascript we use objects (Obj) to implement inheritance, each object has a prototype (Obj.prototype), each of these prototype objects will have its own .prototype all the way up to Object.prototype. In this way we create a prototype chain. The code below exemplifies basic javacript inheritance

We have two objects Cat and Animal, Cat.prototype = new Animal() sets Cat’s prototype to Animal. The prototype link acts only in retrieval. This means that you can now access Animal’s properties and values when creating a new Cat object but making any change to inherited properties will not effect Animal.

After the prototypal inheritance has been set you can still modify the parent constructor and the changes will be visible on all the objects which contain that prototype in the prototype chain (such as Animal.prototype.isAnimal = function() { return true; }).

When attempting to access a property of an object such as fluffly.isAnimal() the prototype link is used (also known as Delegation). Since .isAnimal doesn’t exist in Cat we move up the prototype chain and check Animal, since Animal.isAnimal exists it is returned. If we attempt to call a property which does not exist we still move up the prototype chain up to Object.prototype and return undefined. It is also generally not a good idea to not have a very long prototype chain as this can impact performance.

We can also create inheritance using Object.create in more modern browsers. Stay tuned for a more detailed explanation.

comments powered by Disqus