何时在回调函数名后使用()?

时间:2012-06-08 19:29:46

标签: javascript

  

可能重复:
  In JavaScript, does it make a difference if I call a function with parentheses?

这有什么区别:

$("a").on("click", anotherFunction);

和此:

$("a").on("click", anotherFunction());

有没有办法让没有匿名函数的最后一个自己可执行?

5 个答案:

答案 0 :(得分:3)

第一个传递实际功能;第二个传递函数的返回值。

我不清楚你最后一个问题的含义。

答案 1 :(得分:1)

anotherFunction是对函数的引用。 anotherFunction()是没有参数评估的函数(因此没有引用anotherFunction)。你希望调用一个函数来传递函数的唯一原因就是该函数返回了另一个函数。

答案 2 :(得分:1)

anotherFunction本身就是对函数本身的引用。

anotherFunction()调用函数并导致函数返回的任何内容。

这是一个非常巨大的差异。

这就像是:

之间的区别
function test() {
    alert("Hello!");
}
setTimeout(test,1000); // called after one second
setTimeout(test(),1000); // called immediately, timeout fails.

答案 3 :(得分:0)

你应该使用第一个。这是因为()执行在它们之前定义的函数。如果使用第一个,则只在需要时调用anotherFunction。 JQuery会执行类似anotherFunction(在var命名的回调中)callback()

的操作

答案 4 :(得分:0)

区别在于传递函数引用和调用该函数。

第一种情况(可能是正确的)意味着:当事件发生时调用此函数。

第二个将被解释为:立即调用此函数并使用返回的任何内容作为回调。它最好是我以后可以打电话的功能。

后一种情况仅在函数定义如下时才有效:

function anotherFunction() {
    return function() {
        //real handler
    }
}