传递JavaScript函数作为参数 [英] Pass a JavaScript function as parameter
问题描述
如何在函数没有在父函数中执行或使用 eval()
来传递函数作为参数? (因为我读过它是不安全的。)
我有这个:
addContact(entityId,refreshContactList());
它可以工作,但问题在于 refreshContactList
在函数被调用时触发,而不是在函数中使用。
我可以使用 eval()$根据我读过的内容,这不是最佳做法。如何在JavaScript中传递函数作为参数?
您只需删除括号:
addContact(entityId,refreshContactList);
然后传递该函数而不先执行它。
下面是一个例子:
pre code> function addContact
//你也可以传递参数,如果你需要
// refreshCallback(id);
函数refreshContactList(){
alert('Hello World');
}
addContact(1,refreshContactList);
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.)
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.
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?
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);
这篇关于传递JavaScript函数作为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!