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 Answer 1

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

Sign up to request clarification or add additional context in comments.

3 Comments

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.
To make a library from it, just wrap it in a function makeTemp() {return TEMP; }.
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...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.