1

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.

1 Answers1

2

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?.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • thanks. I was hoping to make this function versatile, and useable in other projects as a library so to speak, but i gues this works. – Richard Clink Apr 13 '18 at 16:40
  • To make a library from it, just wrap it in a `function makeTemp() {`…`return TEMP; }`. – Bergi Apr 13 '18 at 17:20
  • thanks. but darn it, this so called short cut for a private map sucks... i cant do something like "for (TEMP(0) in obj) { newObj[TEMP(0)] = obj[TEMP(0)]}" now i need to think of something else. well, it has its uses... – Richard Clink Apr 13 '18 at 17:47