Object-Oriented JavaScript – Prototypal Class Pattern

Object-Oriented JavaScript – Prototypal Class Pattern

Object-Oriented JavaScript – Prototypal Class Pattern 1280 719 Clark

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:

  1. 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)
  2. instance-by-instance differentiation is done in the constructor
  3. 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.create wires 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 used Object.create, our instance prototype chain (the prototype of the constructor of the instance) points to exampleMethods. The interpreter accesses the .exampleGet property from the exampleMethods object, and returns the property as though it was present on the example instance.
    • line 3: add an example ‘differentiator’ property to the empty object
    • line 4: return the new 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();.