iT邦幫忙

1

JS 如何將new Map()的prototype複製到一個新的class呢?

  • 分享至 

  • xImage

大家好,
最近我在測試 D3.js 時,
試著將 d3.group() 印出,回傳值是 InternMap

一開始以為是 JS 原本就有的物件,但發現不是。
是 d3.js 自己的物件。

重點是,它的結構跟 JS 原本的 new Map(),幾乎一模一樣。

所以我在猜,d3.js 是將 Map 物件,複製一個後,
再新增 _intern_keyprototype 進去。

於是我用了幾個方法,試著複製看看,如下

class InternMap{} //法ㄧ

const InternMap = (data)=>new Map(data) //法二

const InternMap = new Function() //法三
InternMap.prototype = Map.prototype

不過接下來,我就不知道該怎麼做了
/images/emoticon/emoticon19.gif

請問該怎麼複製一個新的 Map 並新增 _intern 跟 _key 進去呢?

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

1
HAO
iT邦研究生 3 級 ‧ 2023-01-19 21:25:40
最佳解答

你好,讓 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]);

https://ithelp.ithome.com.tw/upload/images/20230119/20119338CgfGucXwcf.png

greenriver iT邦研究生 5 級 ‧ 2023-01-30 10:24:37 檢舉

謝謝你
/images/emoticon/emoticon32.gif
幫助很大

我要發表回答

立即登入回答