Long story short:
- Yes, you can (but without using
this)
- No,
this does not mean what you expect it to be
Exporting and closures
In JavaScript (and thus Typescript, as it compiles down to JS) you can export constants and functions directly. From this point of view, there's no difference between a class, a function, or a constant. This becomes more clear if you write a function like this:
export const add = (key, value) => { /*...*/ };
The exported functions will be able to access the cacheMap, and it will be the same object for every time you call this functions. The module itself is evaluated only once, no matter how much times do you import it, so the new Map() part will be executed only once, and only one Map will be created. The object is accessible to these functions because they capture it inside their closure, which is an important language concept for JavaScript. Here is a simple example that illustrates how closure works (but I highly recommend reading a couple of articles on it to understand it completely):
function makeCounter() {
let i = 0; // this variable is inside a closure
return function incrementer() {
// a function declared within a body of another function
// has access to all variables (and functions) declared
// within that body via closure
++i;
return i;
};
}
const counter = makeCounter(); // function call creates a closure with variable `i`
// and all calls below use the same variable from this closure
console.log(counter()); // outputs '1'
console.log(counter()); // outputs '2'
console.log(counter()); // outputs '3'
this
this keyword is quite a misleading concept in JS (or at least unless you are used to it). It is an implicit argument passed to the function when you call it like this:
function f() { console.log(this); }
const obj: any = {x: 1}; // just an object
obj.f = f;
obj.f(); // outputs '{x: 1, f: function}'
// an object before `.f()` is passed to f as 'this'
So using this outside of class methods and some other specific cases is possible, but makes a very little sense. There are some 'reflectish' ways to pass a desired value as this argument into a function, like f.apply({/* object that will be accessible as 'this' inside function body */}), but I highly recommend just using regular arguments for your functions. The this keyword in JS is just another topic that worth reading an article or tutorial on it.
this.cacheMapwill likely be undefined. You probably don't need to usethisat all here, just reference the Map directlycacheMap.set