简体   繁体   中英

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM