So ES 6 is bringing us Maps (and none too soon). Wishing to subclass Map for my own nefarious purposes, I tried the following (abbreviated for clarity):
function
In V8 environments this throws an Error "Map constructor not called with 'new'". Why?
Because new ES6 classes (including builtin ones) are supposed to be only constructable with new
.
SpiderMonkey gets this 'right'
Not exactly. The spec explicitly says
Map
is not intended to be called as a function and will throw an exception when called in that manner.
Wishing to subclass Map
Yes, that's the appropriate thing:
The
Map
constructor is designed to be subclassable. It may be used as the value in anextends
clause of aclass
definition. Subclass constructors that intend to inherit the specifiedMap
behaviour must include asuper
call to the Map constructor to create and initialize the subclass instance with the internal state necessary to support theMap.prototype
built-in methods.
So you'll want to use
class Foo extends Map {
// default constructor
}
var bar = new Foo();
bar.set('foo', 'bar');
You should be able to do something like this:
function Foo() {
return new (Map.bind(this, [].slice.call(arguments)));
}
var bar = new Foo();
For anyone running into this in 2018:
import ES6Map from 'es6-map/polyfill'
class MyMap extends ES6Map {
constructor () {
super()
}
}
Actually, it doesn't really 'work' in FF, since FF also allows to create maps simply by calling Map()
.
However, according to http://kangax.github.io/compat-table/es6/ we do not have compatibility for subclassing in modern browser (fascinating enough, IE has some support here).
tl;dr V8/SpiderMonkey are not fully ES6 compatible yet.