VSO VSO - 1 month ago 12
Javascript Question

Pass a Method to call on Obj as Param

I was initially going to ask how to do it, but it seems you can pass method names just like you can pass property names. Is this bad practice though? Any reason not to do it?

var actionsObj = {
writeSomething: function(){console.log('lol');}
}

function doSomeAction(writeSomething){
actionsObj[writeSomething]();
};

doSomeAction('writeSomething'); //executes writeSomething method of actionsObj


Plnkr

Answer

Is this bad practice though?

No.

Any reason not to do it?

It depends on what you need. Passing a "verb" to a function to choose from a set of pre-set actions is very limited, passing a function itself ("callback") allows the caller to pass arbitrary code.

So this pattern fits if you want to limit the possible actions, or if the set of useful actions is restricted by your domain requirements anyway it doesn't matter, but in other situations it feels a bit inflexible.

Compare

function doSomeAction(actionName){
    var actionsObj = {
        writeSomething: function(x){ console.log(x); },
        …
    };
    actionsObj[actionName]('lol'); 
}

doSomeAction('writeSomething');
doSomeAction('someOtherOption'); // restricted by the callee
…

to

function doSomeAction(action){
    action('lol'); 
}

doSomeAction(function(x){ console.log(x); });
doSomeAction(anyOtherFunction); // chosen by the caller
…

The major difference is where in the code the possible actions are given. Does the doSomeAction need to know about all of them, are they the same every time?