简体   繁体   中英

How to execute a JavaScript function when its name is passed as a string in function?

how can I use function name passed as argument.

example:

showError('container', 'id', '- message', 'show');
showError('container', 'id', '', 'hide');


function showError(container, id, msg, action)
{    
    if(action == 'show') {  
        $('#' + container).show();       
        $('#' + id).html(msg).show();
    }
    else {  
        $('#' + container).hide();       
        $('#' + id).html(msg).hide();
    }

}

obj.foo() really is a 2 step thing. obj.foo returns a function object, and then the () executes it. obj['foo'] returns the same function object, so add a () to execute it.

Since obj['foo'] is the same as obj.foo . Even if the value on that property is a function. So you can always access any property with the [] accessor, using a string as the key name.

$('#' + container)[action]();

Use bracket notation to access the respective method by a string:

function showError(container, id, msg, action) {    
    $('#' + container)[action]();       
    $('#' + id).html(msg)[action]();
}

However, your method looks strange. I'd recommend to limit the action to the two values, and do that automatically:

function showError(container, id, msg) {
    var action = msg=='' ? 'hide' : 'show';
    $('#' + container)[action]();       
    $('#' + id).text(msg)[action]();
}

In the general case, the bracket notation is good. In your case, use toggle :

function showError(container, id, msg, action)
{    
        $('#' + container).toggle(action === 'show');       
        $('#' + id).html(msg).toggle(action === 'show');
}

or even (as Bergi suggests):

function showError(container, id, msg)
{    
        $('#' + container).toggle(!!msg);       
        $('#' + id).html(msg);
}

(It uses my own invention, the double-bang !! , which converts truthy or falsy values to their Boolean equivalents.)

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