Define local function in JavaScript: use var or not?

When a local (inner) function is declared in JavaScript, there are two options:

Declaring with var keyword, assigning to the variable:

(function() {
    var innerFunction1 = function() { ... };
    innerFunction1();
}());

Declaring just with the function keyword, without assigning to variable:

(function() {
    function innerFunction2() { ... };
    innerFunction2();
}());

I can see one advantage of the second: the function can be declared below the code which calls it so it is easier to separate private functions from the code actually executed.

Which of them is better and why ?


Actually there are 3 ways to declare a function:

  • Function declaration: A Function Declaration defines a named function variable without requiring variable assignment. Function Declarations occur as standalone constructs and cannot be nested within non-function blocks. ex: function innerFunction1 () { };

  • Function expression:: A Function Expression defines a function as a part of a larger expression syntax (typically a variable assignment). Functions defined via Function Expressions can be named or anonymous:

    a. Using an anonymous function - var innerFunction1 = function() { };

    b. Using a named function - var innerFunction1 = function myInnerFunction () { };

  • Function constructor: A Function Constructor defines a function dynamically using the Function( ) constructor. Note that the function body is passed to the function as a string argument. var innerFunction1 = new Function (arg1, arg2, ... argN, functionBody)

  • The third method is not recommended because passing the function body as a string may prevent some JS engine optimizations, and it is prone to errors.

    The differences between function declaration and function expression are subtle and you should choose whichever method suits your requirements best.

    I use function expression where I need

  • a singleton function, or
  • to determine which function to use programmatically (using a named function expression).
  • Some differences between a function declaration and a function expression are:

  • Function expressions allow you to assign different functions to the same variable at different points.
  • A function defined by a function declaration can be used before the function declaration itself (or basically anywhere in the current scope), whereas a function defined by a function expression can only be used after the point it is defined.
  • Click here to read the detailed comparison of Function Declaration vs Function Expression vs Function Constructor @MDN

    Note: A function declaration can be easily turned into a function expression by assigning it to a var.

    function foo() {}
    alert(foo); // alerted string contains function name "foo"
    var bar = foo;
    alert(bar); // alerted string still contains function name "foo"
    

    More Reading:

  • http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html
  • http://javascriptweblog.wordpress.com/2010/07/06/function-declarations-vs-function-expressions/
  • http://msdn.microsoft.com/en-us/library/ie/x844tc74%28v=vs.94%29.aspx
  • http://es5.github.io/#x15.3
  • var functionName = function() {} vs function functionName() {}

  • The two notations are functionally equivalent.

    You can assume that:

    function a() {}
    function b() {}
    

    is interpreted as:

    var a, b;
    a = function a() {};
    b = function b() {};
    

    This is why you don't have to declare- (not define!) before-use. You can reassign functions after you've defined them, just like you would with a variable. Functions get hoisted just like variables, because they are variables (mind=blown? good!).


    Declare-before-use

    function a() { b(); } // using b before it's declared?
    function b() {}
    

    becomes:

    var a, b;
    a = function a() { b(); }; // nope! b is declared, we're good
    b = function b() {};
    

    Redefining a function

    function a() { alert("a"); }
    a = function b() { alert("b"); }; // that's weird!
    

    becomes:

    var a;
    a = function a() { alert("a"); };
    a = function b() { alert("b"); }; // oh, that looks normal
    

    Declare vs define

    Declare is: var x . In English: "I will be using variable x ".

    Define is: x = 5 . In English "Variable x now has the value 5 ".

    Declare-before-use is required and enforced in "use strict" . Define-before-use is not required. If your variables are defined in run-time you're good.

    So var x = 5 is both a declaration and a definition, as is function a() {} .

    Be cautious when naming functions not to override an existing variable:

    var a = function () { alert("a"); };
    var b = function a() { alert("b"); };
    a(); // prints "b"
    

    Lint tools will pick up on this.


    When to use which notation?

    I would recommend using the function expression notation ( var a = function () {} ) only when you are reassigned the value of a later on. The function expression then signals to the reader that a is going to get reassigned and that it is intentional.

    Another (minor) argument for the function expression notation is a Lint tool like JSLint that might require you to declare (not define!) your functions before you use them. If you have functions with a recursive definition, ie. a calls b and b calls a , you can not declare one before the other by using the function declaration notation.

    Edit notes: I've made a slight revision about named anonymous functions. It can be usefull to name anonymous functions when you're looking at a stacktrace. The named function will give more context lest it be logged as 'anonymous'.


    The difference is that function with VAR is defined at run-time ,

    whereas function() without VAR is defined at parse-time for a script block.

    That is the only major difference..

    So, user will decide on the requirement basis, which to use, and which suits the requirement..

    链接地址: http://www.djcxy.com/p/94946.html

    上一篇: jQuery的可变语法

    下一篇: 在JavaScript中定义本地函数:使用var还是不使用?