2

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?

2
  • 1
    request[method](url, function(){...}); ... as long as '...' is identical Commented Nov 3, 2015 at 9:41
  • @JaromandaX Thank you, I did not know it:) Commented Nov 3, 2015 at 9:48

2 Answers 2

3

Just use brackets:

request[method](url, function(){...});
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.