如何在函数不在“父”函数中执行或使用eval()的情况下将函数作为参数传递?(因为我读到这是不安全的。)
我有这个:
addContact(entityId, refreshContactList());
它可以工作,但问题是refreshContactList在调用函数时触发,而不是在函数中使用时触发。
我可以使用eval()绕过它,但根据我所读的,这不是最佳实践。如何在JavaScript中传递函数作为参数?
如何在函数不在“父”函数中执行或使用eval()的情况下将函数作为参数传递?(因为我读到这是不安全的。)
我有这个:
addContact(entityId, refreshContactList());
它可以工作,但问题是refreshContactList在调用函数时触发,而不是在函数中使用时触发。
我可以使用eval()绕过它,但根据我所读的,这不是最佳实践。如何在JavaScript中传递函数作为参数?
当前回答
事实上,看起来有点复杂,其实不然。
get方法作为参数:
function JS_method(_callBack) {
_callBack("called");
}
您可以给出以下参数方法:
JS_method(function (d) {
//Finally this will work.
alert(d)
});
其他回答
要将函数作为参数传递,只需删除括号!
function ToBeCalled(){
alert("I was called");
}
function iNeedParameter( paramFunc) {
//it is a good idea to check if the parameter is actually not null
//and that it is a function
if (paramFunc && (typeof paramFunc == "function")) {
paramFunc();
}
}
//this calls iNeedParameter and sends the other function to it
iNeedParameter(ToBeCalled);
这背后的想法是函数与变量非常相似。而不是写作
function ToBeCalled() { /* something */ }
你不妨写
var ToBeCalledVariable = function () { /* something */ }
两者之间有细微的差别,但无论如何,它们都是定义函数的有效方法。现在,如果您定义了一个函数并将其显式分配给一个变量,那么您可以将其作为参数传递给另一个函数,这看起来非常合乎逻辑,而且不需要括号:
anotherFunction(ToBeCalledVariable);
其他答案很好地描述了正在发生的事情,但一个重要的“gotcha”是确保您传递的任何内容都是对函数的引用。
例如,如果传递字符串而不是函数,则会出现错误:
function function1(my_function_parameter){
my_function_parameter();
}
function function2(){
alert('Hello world');
}
function1(function2); //This will work
function1("function2"); //This breaks!
参见JsFiddle
您只需删除括号:
addContact(entityId, refreshContactList);
然后传递函数而不首先执行它。
下面是一个示例:
函数addContact(id,refreshCallback){refreshCallback();//如果需要,也可以传递参数//refreshCallback(id);}函数refreshContactList(){alert(“Hello World”);}addContact(1,refreshContactList);
事实上,看起来有点复杂,其实不然。
get方法作为参数:
function JS_method(_callBack) {
_callBack("called");
}
您可以给出以下参数方法:
JS_method(function (d) {
//Finally this will work.
alert(d)
});
这是另一种方法:
function a(first,second)
{
return (second)(first);
}
a('Hello',function(e){alert(e+ ' world!');}); //=> Hello world