riyoken
riyoken

Reputation: 624

calling a javascript function from a string passed to the function

i have seen multiple questions of a similar nature on here, yet none would work for the specific thing that i have (im using node.js). so for example take this code here.

function command_call(message, socket) {
    if (message.length > 1){
    var func = message[0];
    var string = message.slice(1);
    var string = string.join(' ')}
    else{
    var func = message[0];
    var string = '';};
    if(func[0] == '$') {
    (eval(func.slice(1)))(string, socket);};
};

function say(string, socket){
    socket.write(string)};

if the message passed in to the command_call were to be "$say hi" the function say would be called and return "hi". this works just fine however, if the function that was put to the eval does not exist, it crashes. for instance if the message passed to the command_call were to be "$example blah" it would try to eval "example". basically i need it to check if the function exists before it evals the function. and YES i want to use eval, unless there is a better way to do it in node. and again, this is in node.js

Upvotes: 1

Views: 84

Answers (1)

SLaks
SLaks

Reputation: 887469

You should make an object of functions and use indexer notation:

var methods = { 
    $say: function() { ... }
};

if (!methods.hasOwnProperty(func))
    // uh oh
else
    methods[func]();

Upvotes: 3

Related Questions