如何在js中扩展Map?

问题描述 投票:3回答:3

我正在努力学习js并尝试扩展Map。我做了:

function mapExtend(mapInstance) {
  function MapExtend(){
  }

  MapExtend.prototype = Object.create(Map.prototype);
  MapExtend.prototype.constructor = MapExtend;

  return new MapExtend(mapInstance)
}

我这样做了:

const b = new Map()
mapExtend(b).get(1)

我收到以下错误:

Uncaught TypeError: Method Map.prototype.get called on incompatible receiver #<MapExtend>
    at MapExtend.get (<anonymous>)
    at <anonymous>:1:14

我在这做什么错?

javascript dictionary
3个回答
4
投票

我现在不能给你解释,因为我需要先验证我的假设。

但是使用ES6语法可以扩展:

function mapExtend(mapInstance) {
  class MapExtend extends Map {}

  return new MapExtend(mapInstance)
}

const b = new Map()
mapExtend(b).get(1)

1
投票

您可以直接扩展本机对象的原型。不是每个人都认为good practice

Map.prototype.reportSize = function () {
    return `This map contains ${this.size} ${this.size === 1 ? "entry" : "entries"}`;
};

var x = new Map();
console.log(x.reportSize());
x.set(3, "three");
console.log(x.reportSize());

或者,您可以使用其中的扩展创建自定义函数。这样你就不必延长prototypeMap

const MapWithExtensions = map => {
  return {
    map: map,
    reportSize: function () {
     return `This map contains ${this.map.size} ${
      this.map.size === 1 ? "entry" : "entries"}`; 
    }
  };
};
const myMap = MapWithExtensions(new Map);
console.log(myMap.reportSize());
myMap.map.set(9, "nine");
console.log(myMap.reportSize());
console.log(myMap.map.get(9));

最后,这可能是一种创建扩展Map而不扩展Map原型的方法(实际上,它将Map.prototype键映射到扩展Map中的方法)。

const xMap = MapFactory({
  mySize: function() {return `Hi. My size is currently ${this.size}`}
});
const myMap = xMap.Create();
console.log(myMap.mySize());
console.log("setting [5, \"five\"]")
myMap.set(5, "five");
console.log(myMap.mySize());
console.log(myMap.entries().next().value);

function MapFactory(extensions = {}) {
  const proto = new Map;
  const mappings = Object.getOwnPropertyNames(Map.prototype)
    .reduce( (reduced, key) => { 
      if (proto[key].constructor !== Function) {
        reduced.localProps.push(key);
      } else {
        reduced.proto[key] = function (...args) { return this.map[key](...args); };
      }
      return reduced;
    },
    { localProps: [], proto: {} }
  );
  const XMap = function (map) {
      this.map = map;
      mappings.localProps.forEach( prop =>
        Object.defineProperty(this, prop, { get() {return this.map[prop]; }}) 
      );
  };
  XMap.prototype = {...mappings.proto, ...extensions};
  return { Create: (map = new Map) => new XMap(map) };
}

0
投票

你也可以直接操纵map的原型,如下所示:

let collection =  new Map ();

Map.prototype.customFunc = () => {console.log('customFunc')}

collection.customFunc();
© www.soinside.com 2019 - 2024. All rights reserved.