简体   繁体   中英

JavaScript using variable value as name of object method

I have function with parameters method and url , where method can be equal to get , post , etc. I can do like this

var req = function(method, url) {
    if(method == 'get') {
        request.get(url, function(){...});
    }
    else if(method == 'post') {
        request.post(url, function(){...});
    }
}

or use switch . But I wonder is there any way to do it without using any condition, but calculate variable value during calling of the function?

只需使用括号

request[method](url, function(){...});

In your particular case post and get are properties of the request object, so you can access them with the help of bracket notation :

if(typeof request[method] === 'function') {
    request[method](url, function(){...});
}

You can also use eval() function but it is not recommended, because it makes your code vulnerable for injection attacks, makes it harder to read and debug, and so on.

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