Why isn't Map subclassable in chrome/node?

前端 未结 4 608
无人共我
无人共我 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');
    

提交回复
热议问题