如何在函数不在“父”函数中执行或使用eval()的情况下将函数作为参数传递?(因为我读到这是不安全的。)
我有这个:
addContact(entityId, refreshContactList());
它可以工作,但问题是refreshContactList在调用函数时触发,而不是在函数中使用时触发。
我可以使用eval()绕过它,但根据我所读的,这不是最佳实践。如何在JavaScript中传递函数作为参数?
如何在函数不在“父”函数中执行或使用eval()的情况下将函数作为参数传递?(因为我读到这是不安全的。)
我有这个:
addContact(entityId, refreshContactList());
它可以工作,但问题是refreshContactList在调用函数时触发,而不是在函数中使用时触发。
我可以使用eval()绕过它,但根据我所读的,这不是最佳实践。如何在JavaScript中传递函数作为参数?
当前回答
我用那个问题把头发都剪掉了。我无法让上面的例子发挥作用,所以我最后说:
function foo(blabla){
var func = new Function(blabla);
func();
}
// to call it, I just pass the js function I wanted as a string in the new one...
foo("alert('test')");
这就像一种魅力。。。至少我需要什么。希望这对一些人有所帮助。
其他回答
示例1:
funct("z", function (x) { return x; });
function funct(a, foo){
foo(a) // this will return a
}
示例2:
function foodemo(value){
return 'hello '+value;
}
function funct(a, foo){
alert(foo(a));
}
//call funct
funct('world!',foodemo); //=> 'hello world!'
看看这个
要将函数作为参数传递,只需删除括号!
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);
事实上,看起来有点复杂,其实不然。
get方法作为参数:
function JS_method(_callBack) {
_callBack("called");
}
您可以给出以下参数方法:
JS_method(function (d) {
//Finally this will work.
alert(d)
});
如果要传递函数,只需按名称引用它,而不带括号:
函数foo(x){警报(x);}功能栏(func){func(“Hello World!”);}//提醒“Hello World!”bar(foo);
但有时您可能希望传递包含参数的函数,但在调用回调之前不要调用它。为此,在调用它时,只需将其包装在一个匿名函数中,如下所示:
函数foo(x){警报(x);}功能栏(func){func();}//警告“Hello World!”(通过后从栏内)bar(function(){foo(“Hello World!”)});
若您愿意,也可以使用apply函数,并使用第三个参数,即参数数组,如下所示:
功能饮食(食物1、食物2){警惕(“我喜欢吃”+食物1+“和”+食物2“);}函数myFunc(回调,args){//做一些事情//...//完成后执行回调callback.apply(this,args);}//提醒“我喜欢吃泡菜和花生酱”myFunc(吃,[“泡菜”,“花生酱”]);
如果您可以将整个函数作为字符串传递,这段代码可能会对您有所帮助。
convertToFunc(“运行此('Micheal')”)函数convertToFunc(str){新函数(str)()} 函数runThis(名称){console.log(“Hello”,name)//打印Hello Micheal}