传递JavaScript函数作为参数 [英] Pass a JavaScript function as parameter

查看:101
本文介绍了传递JavaScript函数作为参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在函数没有在父函数中执行或使用 eval()来传递函数作为参数? (因为我读过它是不安全的。)



我有这个:

  addContact(entityId,refreshContactList()); 

它可以工作,但问题在于 refreshContactList 在函数被调用时触发,而不是在函数中使用。



我可以使用 eval()

解决方案

您只需删除括号:

  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆