如何将字符串转换为JavaScript函数调用?

2022-08-30 00:15:21

我得到了一个字符串,如:

settings.functionName + '(' + t.parentNode.id + ')';

我想翻译成一个函数调用,如下所示:

clickedOnItem(IdofParent);

这当然必须在JavaScript中完成。当我做一个警报时,它似乎得到了一切正确的。我只需要调用它将转换为的函数。settings.functionName + '(' + t.parentNode.id + ')';

传说:

settings.functionName = clickedOnItem

t.parentNode.id = IdofParent

答案 1

看到我讨厌eval,我并不孤单

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

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

更完整示例:

/* 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);
}

答案 2
window[settings.functionName](t.parentNode.id);

无需 eval()