Is there any difference between var name = function() {} & function name() {} in Javascript? [duplicate]

CommunityFletcher Moore提出了一个问题:Is there any difference between var name = function() {} & function name() {} in Javascript? [duplicate],或许与您遇到的问题类似。

回答者Matt给出了该问题的处理方式:

They are mostly the same.

utilFunction1 will only be available after it has been declared. utilFunction2 is hoisted to the top of the function, so can be used before it is defined.

function someGlobalFunction() {
  utilFunction1(); // Error: untilFunction1 is undefined :(
  utilFunction2(); // Works

  var utilFunction1 = function() {
  }

  function utilFunction2 () {
  }
}

Unless they are trapped in a closure, both will cease to exist when someGlobalFunction returns.

I prefer to use the method used to declare utilFunction2, but it's up to you.

Declarations of the form utilFunction2 (which are called Function Declarations) have the benefit of being named (i.e. showing up as utilFunction2) in your-favourite-debuggerTM, where as utilFunction1 (called Function Expressions) would just show up as an anonymous function.


For completeness, you also have the form;

var utilFunction3 = function utilFunction4() {
    // blah
};

... which is called a named function expression, which has weird properties (and bugs (in older versions of IE)) of its own.

希望本文对你有帮助,欢迎支持JavaScript中文网