benhowdle89
benhowdle89

Reputation: 37504

Variable name in function call in Javascript

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?

Upvotes: 3

Views: 836

Answers (4)

amaters
amaters

Reputation: 2316

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

wrong answer:

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

should work

Upvotes: -1

Alnitak
Alnitak

Reputation: 340055

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]();

Upvotes: 1

Joseph
Joseph

Reputation: 119887

You might want to use object literals for namespacing instead

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

then calling them:

process[variable]();

Upvotes: 4

pimvdb
pimvdb

Reputation: 154968

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".

Upvotes: 8

Related Questions