3

I'm trying to achieve the following pseudo code:

function processAboutLink(){

}

function processServicesLink(){

}

var variableName = 'about';

process + variableName + Link();

var variableName = 'services';

process + variableName + Link();

I'm aware that the code above isn't real but is a logical representation. Can anyone point me in the right direction?

4 Answers 4

8

It would be more convenient to have an object, because you can access properties dynamically:

var processLinkFunctions = {
  about:    function() { ... },
  services: function() { ... }
};

Then, it's as easy as:

processLinkFunctions[variableName]();

This is basically the same as processLinkFunctions.about() if variableName === "about".

Sign up to request clarification or add additional context in comments.

Comments

4

You might want to use object literals for namespacing instead

var process = {
    services: function(){...},
    about: function(){...}
}

then calling them:

process[variable]();

Comments

1

If you make the functions properties of an object, you can then call them by name (and without resorting to eval !):

var functions = {
    about: function() { ... },
    services: function() { ... }
};

var name = 'about';
functions[name]();

2 Comments

Care to explain why resorting to eval is bad?
@amaters because it leads to insecure code, and potentially undefined behaviour. In ES5 strict mode it's completely disallowed.
-1

EDIT don;t use eval. It seems to be dangerous and leads to undefined behaviour.

wrong answer:

eval('process' + variableName + 'Link()');

should work

4 Comments

Thanks for the pointer T.J. Seems someone downvotes without telling why using eval is bad. Never knew using eval is bad practice.
@amaters sorry, I just couldn't help myself! It's an automatic reaction any time I see eval in an answer...
@amaters yeah, yeah, I know, but it gets tiresome having to explain it every time! I think this was the third answer just today.
answer edited. I learned something as well. Thanks for explaining it over and over. After all we are here to learn.

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.