如何将字符串转换为 JavaScript 函数调用? [英] How to turn a String into a JavaScript function call?
问题描述
我得到了一个字符串:
settings.functionName + '(' + t.parentNode.id + ')';
我想转换成这样的函数调用:
that I want to translate into a function call like so:
clickedOnItem(IdofParent);
这当然必须在 JavaScript 中完成.当我对 settings.functionName + '(' + t.parentNode.id + ')';
发出警报时,似乎一切都正确.我只需要调用它会转换成的函数.
This of course will have to be done in JavaScript. When I do an alert on settings.functionName + '(' + t.parentNode.id + ')';
it seems to get everything correct. I just need to call the function that it would translate into.
图例:
settings.functionName = clickedOnItem
t.parentNode.id = IdofParent
推荐答案
眼看着我讨厌 eval,而我是 不孤单:
Seeing as I hate eval, and I am 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"]
,这将获得对 的引用函数 clickedOnItem (nodeId) {}
.一旦我们在变量中引用了一个函数,我们就可以通过调用变量"来调用这个函数,即 fn(t.parentNode.id)
,它等于 clickedOnItem(t.parentNode.id)
,这是 OP 想要的.
In reply to @Mahan's comment:
In this particular case, settings.functionName
would be "clickedOnItem"
. This would, at runtime translate var fn = window[settings.functionName];
into var fn = window["clickedOnItem"]
, which would obtain a reference to function clickedOnItem (nodeId) {}
. Once we have a reference to a function inside a variable, we can call this function by "calling the variable", i.e. fn(t.parentNode.id)
, which equals clickedOnItem(t.parentNode.id)
, which was what the OP wanted.
更完整的例子:
/* 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 函数调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!