JavaScript Prototypes

I am going to try and help explain the most often misunderstood topic in JavaScript, which is prototypes.

Object Oriented

The first thing to discuss is that JavaScript is a language that actually does object oriented programming that is oriented to objects. While the ECMAScript 2015 standard does allow for the use of the term class, JavaScript really doesn't do the whole class thing, which is really "blueprint oriented" design since with class based inheritance you create a bunch of blueprints to build objects from.

In JavaScript instead of having a blueprint from which you build an object, you have an object with its own set of functionality to which you can point another object so that it can share its functionality. This is done through an objects prototype functions.

Sharing Functionality

So a JavaScript object has functions attached to it as object properties. This allows us to interact with the object without having to pass the object in as an argument and this allows us to limit a function's scope so that we can keep our function names meaningful.

Since JavaScript allows us to attach functions to objects it makes sense that we will attach functionality which we want to be able to use with other objects. So what JavaScript allows us to do is to create an object which is tied to another object in such a way that the new object has access to the functionality of the old object.

There are a couple of ways this can be done in JavaScript and as mentioned above ECMAScript 2015 added an additional syntax to the inheritance options.

What are Prototypes?

Regardless of how you tie two objects together, what you ultimately get is an object with a prototype property that has the functions from the parent object and the parent object has a prototype property with its parent functions and so on.

With JavaScript, we don't have to manually use the prototype function to access the parent's functions. Instead, we just use the function directly and if the current object doesn't have the function then it checks the prototype property to see if the parent object has the function. If it doesn't then it checks its parent and so on up the tree until there is no longer a parent to check.

What this means for us

So the real question is, how does this relate to us in our day to day world of coding? Basically, this means that we create an object to do what we want it to do and then if we need another object which needs some of the same functionality we make the new object based off the old and we have it.

JavaScript allows for a lot of flexibility in inheriting functionality, more so than any other language I have seen. Of course, with more flexibility, it also means that there are more ways you can trip yourself up. Next week I am going to give some examples and discuss specifics of how we can use JavaScript's prototypical inheritance.