Persistence for JavaScript’s Prototype Structures

chrisGoad
2 min readJun 24, 2019

In normal practice, the prototype structure of JavaScript objects is missing from their stored (e.g. JSON) versions. Given the central role of prototypes in JavaScript, this means that, in nearly all cases, one can’t save working components of an application as they are. Instead, application-specific encoding of the components is needed for storage, with associated reconstruction of prototype structure upon retrieval.

However, there is another way. Suppose that we restrict attention to JavaScript objects which are trees with respect to their object-property-value edges, but which retain their instance-to-prototype links. A picture of such a structure appears just above.

Two operations can be defined which in combination make these structures (called, naturally enough, “prototype trees”) suitable for use as components: instantiation (see below) and serialization (that is, conversion into a form suitable for separate storage). Together, these enable the assembly of applications from stored elements.

Serialization is implemented by assigning numeric codes to the nodes of the object graph to be serialized, and then building a JSON-compatible description of the graph, including prototype chains. Here is some code.

Instantiation: Normally, JavaScript instantiation is a one level operation, implemented by Object.create or new, which results in a new object that inherits its properties from the original. For a prototype tree, instantiation involves, very roughly, building a new tree which inherits atomic properties but copies objects. The new tree also retains the structure of prototypical inheritance of the original. The effect is that trees of arbitrary depth can serve as templates from which instances can be spawned at one blow. See this document for a detailed explanation of how instantiation works.

(A technicality: the restriction to trees in terms of object-property-value edges is, in the implementation, relaxed by allowing a third sort of edge: the “cross-tree link”. The details are available in the document cited just above.)

The implementation of prototype trees is open source, under the MIT license. Here is the GitHub repository. Also included in the GitHub repo is code which realizes visual items via SVG. Here are some code samples.

This technology has been applied at PrototypeJungle, a diagramming system which relies entirely on these structures. The visual elements and the diagrams are so represented, both in storage, and in running JavaScript instances. Also, prototype trees form the basis for the user interface, which gives the non-programming user direct access to the prototype structure underlying diagrams.

--

--