看到我讨厌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);
}