Create a class extending from ES6 Map

Alternatively, you can compose the Map() class within your MapWrapper object and expose your own API. The notion of object Composition was not of much in use 5 yrs ago and so, the question and answers were tied to and tangled with Inheritance.


Babel explictly states they do not support extending built-in classes. See http://babeljs.io/docs/usage/caveats/#classes. The reasons are not quite as simple as "limitations in ES5", however, since Map is not an ES5 feature to begin with. It appears that implementations of Map do not support basic patterns such as

Map.prototype.set.call(mymap, 'key', 1);

which is essentially what Babel generates in this case. The problem is that implementations of Map including V8 are overly restrictive and check that the this in the Map.set.call call is precisely a Map, rather than having Map in its prototype chain.

Same applies to Promise.


You should use the good old way:

function ExtendedMap(iterable = []) {
  if (!(this instanceof ExtendedMap)) {
    throw new TypeError("Constructor ExtendedMap requires 'new'");
  }

  const self = (Object.getPrototypeOf(this) === Map.prototype) 
    ? this 
    : new Map(iterable);
  Object.setPrototypeOf(self, ExtendedMap.prototype);

  // Do your magic with `self`...

  return self;
}

util.inherits(ExtendedMap, Map);
Object.setPrototypeOf(ExtendedMap, Map);

ExtendedMap.prototype.foo = function foo() {
  return this.get('foo');
}

Then use new as usual:

const exMap = new ExtendedMap([['foo', 'bar']]);
exMap instanceof ExtendedMap; // true
exMap.foo(); // "bar"

Notice that the ExtendedMap constructor ignore any this binding that isn't a Map.

See also How to extend a Promise.