1
1. $(function () {
       function foo() { return true; }
       log(bar());                        // getting error
       var bar = function() { return true; };   
  });

2. $(function () {
       function foo() { return true; }
       var bar = function() { return true; };
       log(bar());                        // Working   
  });

我的困惑是以下两个声明之间有什么区别,哪个有用?

var bar = function() { return true; };

function bar(){ return true; };
4

2 回答 2

4

The:

function bar(){ return true; };

is function declaration which is hoisted to top by the interpreter, you can call from any place, while:

var bar = function() { return true; };

is function expression you can call only after it is defined. It won't be available before or up in the code just like you were doing:

log(bar());                        // getting error
var bar = function() { return true; }; 

Getting error because on first line bar isn't available yet. To solve that, use function declaration instead if you want.


To learn more about the difference between function declaration and function expression, I highly recommend you to read this great article by Kangax:

于 2012-06-11T06:49:46.593 回答
0

Sarfraz 已经得到了很好的解释。我只是想添加更多,第一个功能,

var bar = function(){ return true; };

更灵活,您可以在声明后添加更多属性或方法:

bar.anotherMethod = function() { alert("This is another method"); }
bar.anotherProperty = 'some value';

虽然function bar(){ return true; }不能那样做。`

于 2012-06-11T06:55:38.110 回答