Javascript Factory Patterns

Jason Sigmon
JSON’s Coding Adventures
3 min readOct 24, 2015

Former Hack Reactor Student Ryan Atkinson wrote a great piece on his blog about Javascript Instantiation Patterns. The highlight of it was the graphic that neatly breaks down the types. What it failed thoroughly explain is why Pseudoclassical is best and how to ensure subclasses maintain all of their features.

Functional Pattern

Functional represents a basic level of understanding, but it does not allow us to take real advantage of constructor functions. You will see everything is recreated with each new object. We are having to reuse code and are going to take a hit to performance

Functional shared

Functional shared is slightly better, but still has many of the same issues that functional does. We have to generate a lot of code just to get our objects built. Despite moving the functions outside of the constructor function, we are still having to formally reference them.

Prototypal

Prototypal serves almost no purpose. If you have made it this far you mind as well, make the jump to Pseudoclassical. You will notice in the example there are some benefits. We can use a prototype; thus, avoiding still having to reference the functions that exist outside of the constructor functions. Unfortunately, we are still reusing code that we should not be.

Pseudoclassical

There is a reason Pseudoclassical has taken prominence within the Javascript community. Its simple and its fast. It allows us to take advantage of prototypal inheritance meaning we can easily reuse code. One thing Ryan left off though is an example of how this becomes powerful.

Example

Our Plane constructor starts with a function called do a barrelRoll. We could pass this down to the sub constructor of Plane called PeppyPlane. Within PeppyPlane we use Plane.call to inherit all of the Plane’s properties. On PeppyPlane, we change the barrelRoll function for new PeppyPlanes, but all other Planes would retain the original barrelRoll function. This is powerful because different sub-constructors can inherit functions and properties while easily personalizing them if needed.

Functional, Functional-Shared, Prototypal
Pseudoclassical, Example

Final Note

As programmers we are always tasked with writing less code that has more power. Functional may be a great way to dip your toes into Object Oriented Programming, but you only realize its true power with Pseudoclassical style.

--

--

Jason Sigmon
JSON’s Coding Adventures

Founder of Arternic, LCS Fan, and tweet @jaysig91. Feel free to reach out and say hello