最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Variable name in function call in Javascript - Stack Overflow

programmeradmin4浏览0评论

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?

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?

Share Improve this question asked Apr 27, 2012 at 12:07 benhowdle89benhowdle89 37.5k74 gold badges207 silver badges340 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 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".

You might want to use object literals for namespacing instead

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

then calling them:

process[variable]();

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

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

wrong answer:

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

should work

发布评论

评论列表(0)

  1. 暂无评论