JavaScript maps (the data type, not the array method) seem set up to accept data (key/value pairs) but not necessarily methods. At least they're not advertised that way. However, we can put methods onto a map instance. Intriguingly, the keyword this
works in such methods, and returns the map itself. For example:
const m = new Map();
m.set('key1', 'value1');
m.get('key1'); // returns 'value1', i.e. standard map usage
m.methodA = function(x) {console.log(x + ' to you too');};
m.methodA('hello'); // shows 'hello to you too'
m.methodB = function() {console.log(this.get('key1'));};
m.methodB(); // shows 'value1'
Is this a proper use of maps and/or methods within maps and/or this
within methods within maps? Or am I corrupting something somehow or breaking some rules by doing this? It seems fairly straight forward and reasonable, making me think it should be OK, but I've never seen or heard anything about this before which makes me nervous.
I can't create a map with a constructor the way I can create an object with a constructor. However, I can create a map factory to produce maps of a given "type". For example, I can use a factory to create maps of the "car type". I can thus also attach methods to each map of this "type" by including them in the factory:
const createCarMap = function(features) {
const carMap = new Map(features);
carMap.set('# tires', 'four (assumed)');
carMap.speakersAreFeatured = function() {
return this.has('speakers');
};
return carMap;
};
const yourCar = createCarMap([
['# cylinders', 'twelve'],
['speakers', 'awesome']
]);
const myCar = createCarMap([
['exterior', 'pearly white']
]);
yourCar.speakersAreFeatured(); // returns true
myCar.speakersAreFeatured(); // returns false
However, such a method will be attached repeatedly for every map produced. This is in contrast to how methods can be added to an object's prototype, allowing method re-usability. So, can methods be attached to a map in a way that allows method re-usability?
My more general question is: Should we be using methods on maps. If so, how? Should we think of them and use them essentially the same way we do with objects, or are there "new rules" for using them with maps? (I suppose one could ask similar questions about other new-ish data types too, e.g. sets, weakMaps, etc., but I'm limiting myself here to maps.)