This question already has answers here:
How to execute a JavaScript function when I have its name as a string

(33个答案)


6年前关闭。




我有一个像这样的字符串:
settings.functionName + '(' + t.parentNode.id + ')';

我想翻译成这样的函数调用:
clickedOnItem(IdofParent);

当然,这必须使用JavaScript来完成。当我对settings.functionName + '(' + t.parentNode.id + ')';发出警报时,似乎一切正确。我只需要调用它将转换为的函数即可。

传奇:
settings.functionName = clickedOnItem

t.parentNode.id = IdofParent

最佳答案

看到我讨厌eval,我是not alone:

var fn = window[settings.functionName];
if(typeof fn === 'function') {
    fn(t.parentNode.id);
}

编辑:回复@Mahan的评论:
在这种情况下,settings.functionName将是"clickedOnItem"。这将在运行时将var fn = window[settings.functionName];转换为var fn = window["clickedOnItem"],这将获得对function clickedOnItem (nodeId) {}的引用。一旦引用了变量中的函数,就可以通过“调用变量”来调用该函数,即fn(t.parentNode.id),等于clickedOnItem(t.parentNode.id),这是OP想要的。

更完整的例子:
/* Somewhere: */
window.settings = {
  /* [..] Other settings */
  functionName: 'clickedOnItem'
  /* , [..] More settings */
};

/* Later */
function clickedOnItem (nodeId) {
  /* Some cool event handling code here */
}

/* Even later */
var fn = window[settings.functionName];
/* note that settings.functionName could also be written
   as window.settings.functionName. In this case, we use the fact that window
   is the implied scope of global variables. */
if(typeof fn === 'function') {
    fn(t.parentNode.id);
}

关于javascript - 如何将字符串转换为JavaScript函数调用? [复制],我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/912596/

10-11 22:00
查看更多