Why isn't Map subclassable in chrome/node?

前端 未结 4 609
无人共我
无人共我 2021-01-21 06:28

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         


        
相关标签:
4条回答
  • 2021-01-21 06:46

    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 an extends clause of a class definition. Subclass constructors that intend to inherit the specified Map behaviour must include a super call to the Map constructor to create and initialize the subclass instance with the internal state necessary to support the Map.prototype built-in methods.

    So you'll want to use

    class Foo extends Map {
        // default constructor
    }
    var bar = new Foo();
    bar.set('foo', 'bar');
    
    0 讨论(0)
  • 2021-01-21 06:53

    You should be able to do something like this:

    function Foo() {
        return new (Map.bind(this, [].slice.call(arguments)));
    }
    
    var bar = new Foo();
    
    0 讨论(0)
  • 2021-01-21 06:59

    For anyone running into this in 2018:

    import ES6Map from 'es6-map/polyfill'
    
    class MyMap extends ES6Map {
      constructor () {
        super()
      }
    }
    
    0 讨论(0)
  • 2021-01-21 07:08

    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.

    0 讨论(0)
提交回复
热议问题