Search code examples
javascriptwindowevalobject-notation

JS - Call function by name (in object notation)


I want to clean up some old code and optimize it, which often uses the same code. (with only different names of functions to call)

I make a easier example and no, I don't write on a game. But this example looks more comprehensible to explaination of my issue.

character.sleep(1);
character.changeName(name);
character.useItm(1423);

Easier Example:

object.function(parameters)

Target was something like this:

myFunc(funcName,value) {
    character.{funcName}(value);
}

$('.btn_sleep') { myfunc('sleep','1'); }
$('.btn_cName') { myfunc('changeName','Harold'); }
$('.btn_uItem') { myfunc('useItem','1423'); }

First I thought about to use eval(), because no user-input will come near of this functions. But I dislike this idea because of the performance lost.

Then I looked around for alternatives and found window[] and new function() as solution.

But I dont get an idea how to use it, when I want to dynamcially call a function by name in an object-notation. (Or in worser cases, when you've to get the result for an if-condtion from a function, which you called with object-notation.)

Could anyone help?


Solution

  • The best way I know how to dynamically call functions is using bracket notation because it allows you to set your object path with a variable

    function myFunc(funcName,value) {
        character[funcName](value);
    }
    
    myfunc('sleep','1');