buy the book to support the author.

Chapter 28. Subclassing Built-ins

JavaScript’s built-in constructors are difficult to subclass. This chapter explains why and presents solutions.

Terminology

We use the phrase subclass a built-in and avoid the term extend, because it is taken in JavaScript:

  • Subclassing a built-in A
  • Creating a subconstructor B of a given built-in constructor A. B’s instances are also instances of A.
  • Extending an object obj
  • Copying one object’s properties to another one. Underscore.js uses this term, continuing a tradition established by the Prototype framework.

There are two obstacles to subclassing a built-in: instances with internal properties and a constructor that can’t be called as a function.

Obstacle 1: Instances with Internal Properties

Most built-in constructors have instances with so-called internal properties (see Kinds of Properties), whose names are written in double square brackets, like this: [[PrimitiveValue]]. Internal properties are managed by the JavaScript engine and usually not directly accessible in JavaScript. The normal subclassing technique in JavaScript is to call a superconstructor as a function with the this of the subconstructor (see Layer 4: Inheritance Between Constructors):

  1. function Super(x, y) {
  2. this.x = x; // (1)
  3. this.y = y; // (1)
  4. }
  5. function Sub(x, y, z) {
  6. // Add superproperties to subinstance
  7. Super.call(this, x, y); // (2)
  8. // Add subproperty
  9. this.z = z;
  10. }

Most built-ins ignore the subinstance passed in as this (2), an obstacle that is described in the next section. Furthermore, adding internal properties to an existing instance (1) is in general impossible, because they tend to fundamentally change the instance’s nature. Hence, the call at (2) can’t be used to add internal properties. The following constructors have instances with internal properties:

  • Wrapper constructors
  • Instances of Boolean, Number, and String wrap primitives. They all have the internal property [[PrimitiveValue]] whose value is returned by valueOf(); String has two additional instance properties:
  • Boolean: Internal instance property [[PrimitiveValue]].
  • Number: Internal instance property [[PrimitiveValue]].
  • String: Internal instance property [[PrimitiveValue]], custom internal instance method [[GetOwnProperty]], normal instance property length. [[GetOwnProperty]] enables indexed access of characters by reading from the wrapped string when an array index is used.
  • Array
  • The custom internal instance method [[DefineOwnProperty]] intercepts properties being set. It ensures that the length property works correctly, by keeping length up-to-date when array elements are added and by removing excess elements when length is made smaller.
  • Date
  • The internal instance property [[PrimitiveValue]] stores the time represented by a date instance (as the number of milliseconds since 1 January 1970 00:00:00 UTC).
  • Function
  • The internal instance property [[Call]] (the code to execute when an instance is called) and possibly others.
  • RegExp
  • The internal instance property [[Match]], plus two noninternal instance properties. From the ECMAScript specification:

The value of the [[Match]] internal property is an implementation dependent representation of the Pattern of the RegExp object.

The only built-in constructors that don’t have internal properties are Error and Object.

Workaround for Obstacle 1

MyArray is a subclass of of Array. It has a getter size that returns the actual elements in an array, ignoring holes (where length considers holes). The trick used to implement MyArray is that it creates an array instance and copies its methods into it:[22]

  1. function MyArray(/*arguments*/) {
  2. var arr = [];
  3. // Don’t use Array constructor to set up elements (doesn’t always work)
  4. Array.prototype.push.apply(arr, arguments); // (1)
  5. copyOwnPropertiesFrom(arr, MyArray.methods);
  6. return arr;
  7. }
  8. MyArray.methods = {
  9. get size() {
  10. var size = 0;
  11. for (var i=0; i < this.length; i++) {
  12. if (i in this) size++;
  13. }
  14. return size;
  15. }
  16. }

This code uses the helper function copyOwnPropertiesFrom(), which is shown and explained in Copying an Object.

We do not call the Array constructor in line (1), because of a quirk: if it is called with a single parameter that is a number, the number does not become an element, but determines the length of an empty array (see Initializing an array with elements (avoid!)).

Here is the interaction:

  1. > var a = new MyArray('a', 'b')
  2. > a.length = 4;
  3. > a.length
  4. 4
  5. > a.size
  6. 2

Caveats

Copying methods to an instance leads to redundancies that could be avoided with a prototype (if we had the option to use one). Additionally, MyArray creates objects that are not its instances:

  1. > a instanceof MyArray
  2. false
  3. > a instanceof Array
  4. true

Obstacle 2: A Constructor That Can’t Be Called as a Function

Even though Error and subclasses don’t have instances with internal properties, you still can’t subclass them easily, because the standard pattern for subclassing won’t work (repeated from earlier):

  1. function Super(x, y) {
  2. this.x = x;
  3. this.y = y;
  4. }
  5. function Sub(x, y, z) {
  6. // Add superproperties to subinstance
  7. Super.call(this, x, y); // (1)
  8. // Add subproperty
  9. this.z = z;
  10. }

The problem is that Error always produces a new instance, even if called as a function (1); that is, it ignores the parameter this handed to it via call():

  1. > var e = {};
  2. > Object.getOwnPropertyNames(Error.call(e)) // new instance
  3. [ 'stack', 'arguments', 'type' ]
  4. > Object.getOwnPropertyNames(e) // unchanged
  5. []

In the preceding interaction, Error returns an instance with own properties, but it’s a new instance, not e. The subclassing pattern would only work if Error added the own properties to this (e, in the preceding case).

Workaround for Obstacle 2

Inside the subconstructor, create a new superinstance and copy its own properties to the subinstance:

  1. function MyError() {
  2. // Use Error as a function
  3. var superInstance = Error.apply(null, arguments);
  4. copyOwnPropertiesFrom(this, superInstance);
  5. }
  6. MyError.prototype = Object.create(Error.prototype);
  7. MyError.prototype.constructor = MyError;

The helper function copyOwnPropertiesFrom() is shown in Copying an Object.Trying out MyError:

  1. try {
  2. throw new MyError('Something happened');
  3. } catch (e) {
  4. console.log('Properties: '+Object.getOwnPropertyNames(e));
  5. }

here is the output on Node.js:

  1. Properties: stack,arguments,message,type

The instanceof relationship is as it should be:

  1. > new MyError() instanceof Error
  2. true
  3. > new MyError() instanceof MyError
  4. true

Another Solution: Delegation

Delegation is a very clean alternative to subclassing. For example, tocreate your own array constructor, you keep an array in a property:

  1. function MyArray(/*arguments*/) {
  2. this.array = [];
  3. Array.prototype.push.apply(this.array, arguments);
  4. }
  5. Object.defineProperties(MyArray.prototype, {
  6. size: {
  7. get: function () {
  8. var size = 0;
  9. for (var i=0; i < this.array.length; i++) {
  10. if (i in this.array) size++;
  11. }
  12. return size;
  13. }
  14. },
  15. length: {
  16. get: function () {
  17. return this.array.length;
  18. },
  19. set: function (value) {
  20. return this.array.length = value;
  21. }
  22. }
  23. });

The obvious limitation is that you can’t access elements of MyArrayvia square brackets; you must use methods to do so:

  1. MyArray.prototype.get = function (index) {
  2. return this.array[index];
  3. }
  4. MyArray.prototype.set = function (index, value) {
  5. return this.array[index] = value;
  6. }

Normal methods of Array.prototype can be transferred via the followingbit of metaprogramming:

  1. [ 'toString', 'push', 'pop' ].forEach(function (key) {
  2. MyArray.prototype[key] = function () {
  3. return Array.prototype[key].apply(this.array, arguments);
  4. }
  5. });

We derive MyArray methods from Array methods by invoking them on the array this.array that is stored in instances of MyArray.

Using MyArray:

  1. > var a = new MyArray('a', 'b');
  2. > a.length = 4;
  3. > a.push('c')
  4. 5
  5. > a.length
  6. 5
  7. > a.size
  8. 3
  9. > a.set(0, 'x');
  10. > a.toString()
  11. 'x,b,,,c'


[22] Inspired by a blog post by Ben Nadel.