2012-01-26 17 views
4

我想知道当我们用圆括号()和不用括号()调用函数时有什么区别。假设,如果我有像调用函数与()和无()之间的区别是什么。当我们将函数分配给变量时?

function($) { 

    var hideAnswers = function() { 

     $('#faqGrid tr td').each(function(){ 

      var $td = $(this); 
      $td.children('div .answer').hide(); 

     }); //end of $('#faqGrid tr td').each(fn) 

    }; //end of var hideAnswers = function() {} 

    var showMessage = function(message){ 

     alert(message); 

    }; //end of var showMessage = function(){} 

    hideAnswers(); //working 
    hideAnswers; // not working 

}(jQuery); // end of function($) { 

第二个hideAnswers的功能;现在在这种情况下工作。另外,我想问我们什么时候分配函数给变量,什么时候没有?

也想,如果我有一个按钮,在点击其中我想调用这个函数,那么我们如何可以调用它就像

<input type="button" onclick = hideAnswers(); /> // is it right? 

如果我也想值传递给这个函数是什么我xhtml页面。像

<input type="button" onclick = showMessage("what is your name "); /> // is it right? 

感谢

+0

尝试,并问一个问题,在一个时间。 SO不适用于洗衣清单=)。 – mrtsherman

回答

4

()会导致函数在其定义中执行代码。如果没有(),你只是简单地指向函数本身 - 这非常有用。您可以将函数存储在变量中并将它们传递给它们。

这可能有助于说明:

function someFunc(){ 
    alert("hello from someFunc"); 
} 

function someOtherFunc(executeMe){ 
    executeMe(); 
} 

someOtherFunc(someFunc); 
2

不同的是,你是不是在调用该函数,如果你不使用()

只是写入函数的名称(如hideAnswers)什么都不做。它用于将函数作为参数传递给另一个函数或将其分配给一个变量,例如。它不叫它。

相关问题