Delegate Prototypes and Unintended Side-effects

Nick Best
2 min readNov 9, 2019

--

Striving For Professionalism

Flexibility, conciseness, and reuse-ability are traits that help keep one’s code from developing a smell. Achieving these traits is not straightforward. It is the professional coder’s duty to fully understand the language they are working with in order to express themselves fluently and idiomatically.

Doing Away with Constructors

When using JavaScript this means one must not bring classical inheritance patterns over to a language that has the power of prototypal inheritance. The constructor is one such pattern that wastes time and space and leads one to modelling inheritance relationships as is-a vs. has-a or uses-a, making your code less flexible and re-useable.

Delegate Prototypes

Prototype delegation is one way of employing prototypal inheritance and ridding your code of constructors. Using the Object.create() method, one can create any number of new object instances that have an internal reference to the object passed into that method. When an object is queried for a property or method, it first checks itself, then it checks its delegate prototype, then that object’s delegate prototype, and so on, all the way down the “prototype chain”. Properties on the prototype will act like defaults but will be overridden when set on the new instance. When you set these properties it will only override the value for instance.

However…

One pitfall that developers may fall into with delegate prototypes is mutating an object or array that is a property of the delegate prototype and the new instance. Consider the following contrived example:

In the code above, the last line will log baz to the console. When we mutate the data object on foo1, the reference to that object is shared by fooProto and foo2, so those object instances will reflect that mutation. To get around this one must replace the entire property, as in the following:

Because of the potential unintended consequences that can happen, sharing non-method data on a prototype property is an anti-pattern in JavaScript.

Practice your understanding

If you’d like you can practice solving questions like this and other potential interview questions by checking out this repo: https://github.com/bicknest/coding_interview_problems

All of the problems come with unit tests, so when you write your own solution you can see if your solution is correct!

Resources used in writing this post:

Programming JavaScript Applications by Eric Elliott

--

--