How do the ES6 Map shims work

后端 未结 3 1341
不知归路
不知归路 2021-02-13 07:24

Based on my understanding of the docs (here and here) one would need a reference to the memory address for it to work:

const foo = {};
const map = new Map();
ma         


        
3条回答
  •  南方客
    南方客 (楼主)
    2021-02-13 07:57

    Have a look at my polyfill here. I am not advertising my polyfill, rather all I am saying is that it is the simplest and most straightforward I have yet to find, and thus it is the most suitable for learning and educational analysis. Basically, how it works is it uses a lookup table for the keys and a corresponding value table as visualized below.

    var k = {}, j = [], m = document, z = NaN;
    var m = new Map([
        [k, "foobar"], [j, -0xf], [m, true], [z, function(){}]
    ]);
    
    
    
    
    Index      Key                 Value
    ##### ################    ################
    0.    k ({})              "foobar"
    1.    j ([])              -15
    2.    m (Document)        true
    3.    z (NaN)             function(){}
    

    Internally, each item is stored at a different index, or at least that is the way I like to do it. This is also similar to the way the browser implements it internally. Unfortunately, I have seen some other polyfills that attempt to instead store the key on the object itself, and mess with all the internal methods to hide it, resulting in the entire webpage running 10000% slower and the maps being so slow that it takes nearly a full millisecond just to set and get new properties. Plus, I cannot fathom how many countless hours they waisted just trying to monkey-patch all the internal methods such as hasOwnProperty.

    As for how and why my polyfill works, javascript objects are stored at a different place in memory. That is why [] !== [] and indexOf on an array of javascript objects works properly. It is because they are not the same array.

提交回复
热议问题