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
313 views
in Technique[技术] by (71.8m points)

javascript - 将JavaScript函数作为参数传递(Pass a JavaScript function as parameter)

How do I pass a function as a parameter without the function executing in the "parent" function or using eval() ?(如何在没有“父”函数中执行的函数或使用eval()情况下将函数作为参数传递?)

(Since I've read that it's insecure.)((因为我读过它是不安全的。)) I have this:(我有这个:) addContact(entityId, refreshContactList()); It works, but the problem is that refreshContactList fires when the function is called, rather than when it's used in the function.(它可以工作,但问题是refreshContactList在调用函数时触发,而不是在函数中使用它时触发。) I could get around it using eval() , but it's not the best practice, according to what I've read.(我可以使用eval()绕过它,但根据我所读到的,这不是最好的做法。) How can I pass a function as a parameter in JavaScript?(如何在JavaScript中将函数作为参数传递?)   ask by imperium2335 translate from so

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

1 Reply

0 votes
by (71.8m points)

You just need to remove the parenthesis:(您只需要删除括号:)

addContact(entityId, refreshContactList); This then passes the function without executing it first.(然后,它会先传递函数而不先执行它。) Here is an example:(这是一个例子:) function addContact(id, refreshCallback) { refreshCallback(); // You can also pass arguments if you need to // refreshCallback(id); } function refreshContactList() { alert('Hello World'); } addContact(1, refreshContactList);

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

...