Variable name in function call in Javascript

I am trying to execute the following pseudo code:

function processAboutLink(){

}

function processServicesLink(){

}

var variableName = 'about';

process + variableName + Link();

var variableName = 'services';

process + variableName + Link();

I know that the code above is not real, but is a logical representation. Can someone point me in the right direction?

+3
source share
4 answers

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

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

Then it is as simple as:

processLinkFunctions[variableName]();

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

+8
source

Instead, you can use object literals instead of namespacing

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

then calling them:

process[variable]();
+4
source

, ( eval!):

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

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

, eval. undefined.

:

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

-1
source

All Articles