Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using javascript objects as a "function store" and calling them dynamically?

Consider something like this:

const keyAction = {
    a() {
        console.log("You've pressed 'a'");
    },
    b() {
        console.log("You've pressed 'b'");
    },
    c() {
        console.log("You've pressed 'c'");
    }
}

document.addEventListener('keydown', e => keyAction[e.key]());

Is this a bad practice? Are there any reason to not do it this way?

like image 572
Balázs Sáros Avatar asked Oct 23 '25 01:10

Balázs Sáros


1 Answers

It's a popular practice actually, as some people tend to use objects to simulate namespaces from other languages. I think there's nothing bad with it, as long as you understand the traps that this approach may set. For example you should keep in mind what happens to this when you pass these functions as parameters (look at the example below):

const store = {
    a() {
        this.b();
    },
    b() {
        console.log("It works!");
    }
}

store.a();  // Logs "It works"
setTimeout(store.a, 10) // Error: this.b is not a function

Also, as noted by @Nick Ovchinnikov, in your specific example there is one other pitfall. You should make sure, that whenever a button is pressed, the environment will not try to invoke a function which doesn't exist - otherwise you might encounter an error. So eventually your handler binding should look somewhat like this:

document.addEventListener('keydown', e => {
    if (typeof keyAction[e.key] === 'function') {
        keyAction[e.key]();
    }
});
like image 163
Szab Avatar answered Oct 24 '25 14:10

Szab