The Prototypal Class pattern is fundamental to JavaScript, especially object-oriented JavaScript. Though used infrequently by developers, this pattern underpins the syntactic sugar provided by the new keyword and the ES6+ class — thus, worth learning. The important characteristics of the Prototypal Class pattern are the following:
- shared functionality is stored in a container object outside the constructor function object (shared methods are not stored as properties on the instance returned by the constructor)
- instance-by-instance differentiation is done in the constructor
- failed property lookup is delegated to the container object holding the desired shared methods
This pattern only creates a single instance of each shared method, regardless of how many instances of the ‘class’ are created, thus saving overhead.
This is the pattern on top of which the pseudo-classical pattern is built — adding some syntactic sugar. Because of the frequency of use of the pseudo-classical pattern, it is important to understand this prototypal class pattern first.
Let’s close by dissecting the important parts of the example above:
- lines 1 – 5: the constructor function
- line 2: create an empty object and delegate its failed property lookups to the exampleMethods object
Object.createwires up the prototype and constructor properties for the instance (example, in our case)- When attempting to access a nonexistent property (
.exampleGet) on the new instance (example), instead of an error, the interpreter will ‘look up the prototype chain.’ Because we usedObject.create, our instance prototype chain (the prototype of the constructor of the instance) points toexampleMethods. The interpreter accesses the.exampleGetproperty from theexampleMethodsobject, and returns the property as though it was present on theexampleinstance.
- line 3: add an example ‘differentiator’ property to the empty object
- line 4: return the new object
- line 2: create an empty object and delegate its failed property lookups to the exampleMethods object
- lines 7 – 14: method container object with example methods
We can now create as many Example instances as we want, all with access to the methods contained within exampleMethods. It is as simple as var example = Example();.