Working on some project I noticed myself using the memoization pattern many times to create lazy evaluated properties. With ES5 a new way of implementing lazy attributes becomes available, preserving the interface of an attribute.
Given the following example object containing a property
Our goal is to only evaluate the expression for
obj.expensive if it is really necessary.
The most common way to achieve this is using a function and memoization.
This way the value is just calculated once at the time
obj.expensive is actually used.
This is a lot of boilerplate, so let’s factor most things out into a function
Much better. But still the interface to the user of
obj changes from
The ES5 Way – Getters
Using getters the code can be improved even more in order to preserve the interface to the user.
You may have noticed, that property descriptors and
Object.create are used
to define the property. Since descriptors allow to specify additional meta information on the mutability and visibility of a property I try to use them when ever possible (and appropriate).
Off topic: Other property descriptor helpers
Here are just two of the helper functions I usually use to define property descriptors
Using those an object definition can look like
ES6 Arrow Functions
This even looks nicer using ES6 Arrow Functions