JavaScript Prototype Pattern

javascript prototype pattern

There are many ways to structure JavaScript code using various design patterns in an effort to produce software that is easier to reason about as well as reusable and maintainable. One such pattern is the prototype pattern. As we know, JavaScript itself uses prototyping as a means of augmenting the built in objects. With the prototype pattern, you can directly extend JavaScript objects and arrange your code in such a way as you might with a more traditional object oriented approach that you might find in Java or PHP. Let’s have a closer look at the JavaScript Prototype Pattern now.


What are the benefits and drawbacks of the Prototype Pattern?

To recap, Prototyping allows a developer to extend an object, or override existing methods that the object makes available to the user. Since this is native to how JavaScript works, we can consider this a good benefit. By making use of the JavaScript Prototype Pattern, you can better modularize your code. We saw the beginnings of this in our example of closure article. Here are some benefits and drawbacks.

Benefits

  • Prototyping is native to JavaScript
  • Allows you to extend an existing object
  • Facilitates code modularization
  • Takes variables and functions out of the global namespace
  • Functions load into memory one time only

Drawbacks

  • Heavy use of the ‘this’ keyword can cause confusion
  • Requires both a Constructor and a Function Prototype

That last point can almost be seen as a benefit actually. The reason is, the constructor is going to contain all the variables. Each time a new instance is made, you’ll get a fresh set of variables to work with. This is how you can have an instance of a house where it’s color is red, and another instance of a house where it’s color is blue. The functions reside in the prototype section of the pattern, and the big benefit here is that no matter how many instances of the particular constructor or “class” you are dealing with, each individual function is loaded only one time into memory. With these quick examples of benefits and drawbacks, let’s have a look at the structure of a prototype pattern.


Structure of Prototype Pattern

The way that the prototype pattern works is that you first define an object and associate it with a constructor. By convention the name of the object will be capitalized. The code will work just the same if you do not set the first letter as uppercase, but this convention is a good way to indicate that when calling this code later it will be making use of the new keyword. As we mentioned, the prototype pattern makes use of the this keyword as well. In fact a good refresher if needed is to read our what this refers to article along with how the new keyword works in JavaScript tutorial. Let’s see an example of this pattern.

Click Clear

When you run this example code, you can see it outputs the result based on the data we pass in. We used the new keyword to create a new instance of a Bicycle, passing in the brand of ProdecoTech, which is a really cool electric bicycle brand. Then, we can call methods off of that new object we have. We demonstrate this by calling bike.goForward() passing in a 100 percent value. If all works correctly, we see ProdecoTech Bicycle Moving forward at 100 percent speed! output to the screen. Now that you have a Constructor, you can new up as many different instances as you might need. This is analogous to creating new objects in class based languages. Let’s try it out.

Click Clear

When we set up the Function Prototype for our Bicycle, we assigned an object literal to the prototype. An object literal consists of one or many key value pairs. So far we only have one key, and one value. The key is ‘goForward’ and the value is an anonymous function. What this means is that all objects that are newed up from this Bicycle constructor will have access to that particular method. If you have a bicycle, and all you can do is go forward, you may get into trouble when it comes time to stop. It would be wise that all bicycles have the ability to slow down or stop. We can add this to all bicycles by simply extending their functionality by adding an additional key value pair to the object literal assignment in the function prototype. All you have to do is add a comma after the first key value pair and then add another key value pair as needed. Let’s see.

Extending The Prototype

With our function prototype updated, we should be able to have any instance of a Bicycle make use of either method.

Click Clear

We can see that it is working quite well now for all bicycles.


More Global Abatement With Namespaces

With the prototype pattern, we are taking functions and variables out of the global namespace. When we call code that makes use of this pattern however, those new instances of a constructor will reside in the global namespace. To mitigate even this level of global variables, we can create our own unique namespace to contain our code. Here is our example code, now making use of an object to add this namespace. All we have to do is create a variable and assign it to itself if it exists, or assign an empty object if it does not. Then you just prefix the other parts of the code to make use of the namespace.


JavaScript Prototype Pattern Summary

In this tutorial, we’ve seen how the javascript prototype pattern can be used to structure JavaScript in a more concise manner leading to better code organization. The main benefits of this pattern are code reuse, maintenance simplification, and removing variables and functions from the global namespace. Removing variables and functions from the global namespace is especially important since there will almost always be several collections of different JavaScript libraries on a page, and we don’t need any naming collisions that can lead to bugs and breakage. The Prototype Pattern makes use of the prototyping functionality built right in to the language. This makes it a natural extension to the language itself. Functions load into memory only once with the prototype pattern, leading to good performance. Finally, we saw that when using the Prototype pattern, you will always have two sections – one for the constructor itself, and another for the prototyping area where methods are defined. And with that, we have a solid introduction to the JavaScript Prototype Pattern.