大家好,
最近我在測試 D3.js 時,
試著將 d3.group() 印出,回傳值是 InternMap。
一開始以為是 JS 原本就有的物件,但發現不是。
是 d3.js 自己的物件。
重點是,它的結構跟 JS 原本的 new Map(),幾乎一模一樣。

所以我在猜,d3.js 是將 Map 物件,複製一個後,
再新增 _intern 跟 _key 的 prototype 進去。
於是我用了幾個方法,試著複製看看,如下
class InternMap{} //法ㄧ
const InternMap = (data)=>new Map(data) //法二
const InternMap = new Function() //法三
InternMap.prototype = Map.prototype
不過接下來,我就不知道該怎麼做了![]()
請問該怎麼複製一個新的 Map 並新增 _intern 跟 _key 進去呢?
你好,讓 InternMap 繼承 Map 即可,下方是簡單的實現方式供參考:
class InternMap extends Map {
_intern = new Map();
set(key, value) {
super.set(key, value);
this._intern.set(key, key);
}
}
實例化後透過 set 添加資料即可重現:
const obj = new InternMap();
obj.set('name1', [1, 2, 3, 4, 5]);
