VSO VSO -4 years ago 99
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){

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


Answer Source

Is this bad practice though?


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.


function doSomeAction(actionName){
    var actionsObj = {
        writeSomething: function(x){ console.log(x); },

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


function doSomeAction(action){

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?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download