Is there a way to do the code below as a Class extending Function? if not is there a better way of doing it? I do not want to use anything other than standard vanilla JavaScript
Function.prototype._data = new Map();
function TEMP (key) { return TEMP._data.get(key) }
TEMP.remove = function(id) { TEMP._data.delete(id) };
TEMP.reset = function() { TEMP._data.clear()};
TEMP.store = function(key, val) { TEMP._data.set(key, val) }
Currently this is what the class looks like:
class Temp extends Function {
constructor(){
super();
this._data = new Map();
}
remove(key) { this._data.delete(key) }
reset() { this._data.clear() }
store(key, val) { this._data.set(key, val) }
};
I am new to Stack Overflow, and could not find the answer anywhere.
The better way is not to involve Function.prototype
. Just do
function TEMP (key) { return TEMP._data.get(key) }
TEMP._data = new Map(); /*
^^^^^^^^^^^^ */
TEMP.remove = function(id) { TEMP._data.delete(id) };
TEMP.reset = function() { TEMP._data.clear()};
TEMP.store = function(key, val) { TEMP._data.set(key, val) }
Since there is only one TEMP
with a single Map
in your program, there's no reason to involve a class
here.
If you need multiple instances, and insist on extending Function
for that instead of using a simple factory, see How to extend Function with ES6 classes?.