I am designing a small library, and trying to keep the API as small as possible, the idea of using a function as a dictionary/object itself looks appealing.
The idea is to be able to call a function normally like:
fn('hello', 'some other extra info to be processed', etc...)
This call will process the information and then store it somewhere. This processed information can be accessed in certain conditions (not the typical use case), and it would be great to fetch information in this fashion:
fn['hello']
//-> some stuff
In python for instance it would be very easy to overload the []
operator,
but AFAIK there is not an easy and reliable way in JS that works in most
environments (proxies seem to do the trick, but we are not so far yet). Getters and setters are not an option since the user can input any value.
Therefore, I am left with setting attributes of the function object, which seems hacky because I might overwrite the original attributes of the function, for instance:
apply
prototype
__proto__
However, many things in the JS world are hacky and we happily do them everyday. The question: is this unsafe and will lead to the death of thousands of kittens?
You could use setter and getter functions for it.
The disadvantage is, you have to know in advance which keys you use.
function fn(s) {
if (!fn[s]) {
Object.defineProperty(fn, s, { get: function () { document.write('hello '+s+'!<br>'); }, set: function () { } });
}
document.write('hello ' + s + '<br>');
}
fn('stackoverflow');
fn['stackoverflow'];
fn('42');
fn['42'];
fn['stackoverflow'];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With