Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
276 views
in Technique[技术] by (71.8m points)

javascript - 如何将String转换为JavaScript函数调用? [重复](How to turn a String into a JavaScript function call? [duplicate])

This question already has an answer here:(这个问题在这里已有答案:)

I got a string like:(我有一个字符串:)

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

that I want to translate into a function call like so:(我想要转换成函数调用,如下所示:)

clickedOnItem(IdofParent);

This of course will have to be done in JavaScript.(这当然必须在JavaScript中完成。)

When I do an alert on settings.functionName + '(' + t.parentNode.id + ')';(当我在settings.functionName + '(' + t.parentNode.id + ')';上发出警报时settings.functionName + '(' + t.parentNode.id + ')';) it seems to get everything correct.(它似乎让一切都正确。) I just need to call the function that it would translate into.(我只需要调用它将转换成的函数。)

Legend:(传说:)

settings.functionName = clickedOnItem

t.parentNode.id = IdofParent
  ask by SpoiledTechie.com translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Seeing as I hate eval, and I am not alone :(看到我讨厌eval,而我并不孤单 :)

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

Edit: In reply to @Mahan's comment: In this particular case, settings.functionName would be "clickedOnItem" .(编辑:回复"clickedOnItem"的评论:在这种特殊情况下, settings.functionName将是"clickedOnItem" 。)

This would, at runtime translate var fn = window[settings.functionName];(这将在运行时翻译var fn = window[settings.functionName];) into var fn = window["clickedOnItem"] , which would obtain a reference to function clickedOnItem (nodeId) {} .(进入var fn = window["clickedOnItem"] ,它将获得对function clickedOnItem (nodeId) {}的引用。) Once we have a reference to a function inside a variable, we can call this function by "calling the variable", ie fn(t.parentNode.id) , which equals clickedOnItem(t.parentNode.id) , which was what the OP wanted.(一旦我们在变量中引用了一个函数,我们可以通过“调用变量”来调用这个函数,即fn(t.parentNode.id) ,它等于clickedOnItem(t.parentNode.id) ,这就是OP通缉。)

More full example:(更完整的例子:)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...