传递一个 JavaScript 函数作为参数 [英] Pass a JavaScript function as parameter
问题描述
如何将函数作为参数传递而不在父"函数中执行函数或使用 eval()
?(因为我已经读过它不安全.)
How do I pass a function as a parameter without the function executing in the "parent" function or using eval()
? (Since I've read that it's insecure.)
我有这个:
addContact(entityId, refreshContactList());
它有效,但问题是 refreshContactList
在调用函数时触发,而不是在函数中使用时触发.
It works, but the problem is that refreshContactList
fires when the function is called, rather than when it's used in the function.
我可以使用 eval()
解决这个问题,但根据我的阅读,这不是最佳实践.如何在 JavaScript 中将函数作为参数传递?
I could get around it using eval()
, but it's not the best practice, according to what I've read. How can I pass a function as a parameter in JavaScript?
推荐答案
你只需要去掉括号:
addContact(entityId, refreshContactList);
然后传递函数而不先执行它.
This then passes the function without executing it first.
这是一个例子:
function addContact(id, refreshCallback) {
refreshCallback();
// You can also pass arguments if you need to
// refreshCallback(id);
}
function refreshContactList() {
alert('Hello World');
}
addContact(1, refreshContactList);
这篇关于传递一个 JavaScript 函数作为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!