将JavaScript函数作为参数传递

imp*_*335 624 javascript parameters function

如何在没有"父"功能中执行的功能或使用eval()?的情况下将函数作为参数传递?(因为我读过它是不安全的.)

我有这个:

addContact(entityId, refreshContactList());
Run Code Online (Sandbox Code Playgroud)

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

eval()根据我所读到的内容,我可以使用它,但这不是最好的做法.如何在JavaScript中将函数作为参数传递?

Fen*_*ton 873

您只需要删除括号:

addContact(entityId, refreshContactList);
Run Code Online (Sandbox Code Playgroud)

然后,它会先传递函数而不先执行它.

这是一个例子:

function addContact(id, refreshCallback) {
    refreshCallback();
    // You can also pass arguments if you need to
    // refreshCallback(id);
}

function refreshContactList() {
    alert('Hello World');
}

addContact(1, refreshContactList);
Run Code Online (Sandbox Code Playgroud)

  • @stevefenton,考虑用h2ooooooo评论更新你的答案,它会非常有用. (6认同)
  • 基于这个问题,回调函数不接受参数,这就是我将它们排除在示例之外的原因.我会添加一个评论. (5认同)
  • @Veverke它看起来像这样......`addContact(1,function(id){console.log(id);});` (4认同)
  • @Steve Fenton:看完你的回复后我问自己为什么要问...... :-) (4认同)

dal*_*lin 302

如果要传递函数,只需按名称引用它而不使用括号:

function foo(x) {
    alert(x);
}
function bar(func) {
    func("Hello World!");
}

//alerts "Hello World!"
bar(foo);
Run Code Online (Sandbox Code Playgroud)

但有时您可能希望传递包含参数的函数,但在调用回调之前不要调用它.要做到这一点,在调用它时,只需将其包装在匿名函数中,如下所示:

function foo(x) {
   alert(x);
}
function bar(func) {
   func();
}

//alerts "Hello World!" (from within bar AFTER being passed)
bar(function(){ foo("Hello World!") });
Run Code Online (Sandbox Code Playgroud)

如果您愿意,还可以使用apply函数并使用第三个参数作为参数数组,如下所示:

function eat(food1, food2)
{
    alert("I like to eat " + food1 + " and " + food2 );
}
function myFunc(callback, args)
{
    //do stuff
    //...
    //execute callback when finished
    callback.apply(this, args);
}

//alerts "I like to eat pickles and peanut butter"
myFunc(eat, ["pickles", "peanut butter"]); 
Run Code Online (Sandbox Code Playgroud)

  • 这应该排名更高,因为他还解决了如何传递带参数的函数 (62认同)
  • 当然这必须是公认的答案. (6认同)
  • 对于“将其包装在匿名函数中”示例,如果不明显,匿名函数返回函数本身(带参数),并在到达 func() 中的括号时调用。这花了我一段时间才弄明白,所以我认为它可能会帮助其他人。 (4认同)
  • 我将添加的内容是,仅此功能 - 能够将JavaScript函数作为参数或变量等传递 - 是*功能*,它使JavaScript变得如此强大并且非常适合编码. (3认同)
  • 我非常感谢Javascript提供此功能,并感谢@dallin让我知道它存在. (3认同)

小智 51

例1:

funct("z", function (x) { return x; });

function funct(a, foo){
    foo(a) // this will return a
}
Run Code Online (Sandbox Code Playgroud)

例2:

function foodemo(value){
    return 'hello '+value;
}

function funct(a, foo){
    alert(foo(a));
}

//call funct    
funct('world!',foodemo); //=> 'hello world!'
Run Code Online (Sandbox Code Playgroud)

看这个


nai*_*sts 34

要将函数作为参数传递,只需删除括号!

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); 
Run Code Online (Sandbox Code Playgroud)

这背后的想法是函数与变量非常相似.而不是写作

function ToBeCalled() { /* something */ }
Run Code Online (Sandbox Code Playgroud)

你不妨写一下

var ToBeCalledVariable = function () { /* something */ }
Run Code Online (Sandbox Code Playgroud)

两者之间存在细微差别,但无论如何 - 它们都是定义函数的有效方法.现在,如果您定义一个函数并将其显式分配给变量,那么您可以将其作为参数传递给另一个函数,并且您不需要括号:

anotherFunction(ToBeCalledVariable);
Run Code Online (Sandbox Code Playgroud)

  • 只是`typeof paramFunc =="function"`就足够了,因为如果它不可调用,那么你可以忽略它. (2认同)

ser*_*0ne 15

JavaScript程序员中有一句话:"Eval is Evil",所以尽量避免它!

除了Steve Fenton的回答,您还可以直接传递函数.

function addContact(entity, refreshFn) {
    refreshFn();
}

function callAddContact() {
    addContact("entity", function() { DoThis(); });
}
Run Code Online (Sandbox Code Playgroud)


Fen*_*ras 7

我把那个问题剪掉了。我无法使以上示例正常工作,所以我结束了:

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')");
Run Code Online (Sandbox Code Playgroud)

这就像一种魅力……至少对于我需要的东西。希望对您有所帮助。

  • 支持首句xD (5认同)

Nar*_*sim 6

我建议将参数放在一个数组中,然后使用该.apply()函数将它们拆分.所以现在我们可以轻松地传递一个包含大量参数的函数,并以一种简单的方式执行它.

function addContact(parameters, refreshCallback) {
    refreshCallback.apply(this, parameters);
}

function refreshContactList(int, int, string) {
    alert(int + int);
    console.log(string);
}

addContact([1,2,"str"], refreshContactList); //parameters should be putted in an array
Run Code Online (Sandbox Code Playgroud)


Nul*_*ter 5

你也可以eval()用来做同样的事情.

//A function to call
function needToBeCalled(p1, p2)
{
    alert(p1+"="+p2);
}

//A function where needToBeCalled passed as an argument with necessary params
//Here params is comma separated string
function callAnotherFunction(aFunction, params)
{
    eval(aFunction + "("+params+")");
}

//A function Call
callAnotherFunction("needToBeCalled", "10,20");
Run Code Online (Sandbox Code Playgroud)

而已.我也在寻找这个解决方案并尝试在其他答案中提供的解决方案,但最终从上面的例子中得到了它.