What are JavaScript Prototypes?

A JavaScript Prototype refers to JavaScripts object linking model, and how objects link to one another.

Objects in programming are entities that have properties (make, colour) and methods (brake, changeGear).

If you’re familiar with "Class based" object oriented languages. They use a "Class" to describe what an object should look like, almost like a blueprint or stamp on a press. When objects are created the properties and methods are copied from the Class to those objects. JavaScript on the other hand doesn't follow this Class copying model, it simply has objects, with references (or pointers) to other objects.

A good way of thinking about it is to imagine a websites sitemap tree, every object has a reference to it’s parent object. For example there may be many secondary level pages that point to the homepage as their parent, and many tertiary level pages that point to the secondary level as their parent, building up a tree.

In the case of JavaScript the homepage would be the root "Object", and other objects are created with their prototypes pointing to the root object.

However when it comes to resolving and calling properties and methods on an object a good way of thinking about that is with layers.

-- Car prototype points to Vehicle below

--- Vehicle prototype points to the base object below

---- base object prototype points to null

Imagine each of these objects has properties and methods on them. Now shift the perspective as if you were looking down on these layers. It would appear as though Car has all the properties and methods, but this is just an illusion. The properties and methods missing from Car are delegated to it’s prototype link and so on, the missing properties are in fact coming from the layers behind. This is what makes prototypes powerful, allowing objects to delegate to their prototype object when it doesn’t actually have a property or method itself.

These "prototype chains" can grow to allow a lot of flexibility. Though there are gotchas to watch out for, such as the 'this' and 'new' keywords. As well as a functions .prototype property, which unfortunately due to it's name can become confusing.

I hope this has helped explain the basics of what JavaScript Prototypes are, and gives a few mental models to understand the structure.

For more information on the gotchas I highly recommend reading this book from the You Don’t Know JS series.

This post is part of a series explaining technical subjects in simple terms, inspired by a quote from physicist Richard Feynman "If you can't explain something in simple terms, you don't understand it", Stay tuned.