What is the difference between these two functions/approaches?

前端 未结 4 1512
南旧
南旧 2020-12-06 07:10

I use only jQuery for writing JavaScript code. One thing that confuses me is these two approaches of writing functions,

First approach



        
相关标签:
4条回答
  • 2020-12-06 07:40

    The first is a function expression assigned to the vote variable, the second is a function declaration.

    The main difference is that function statements are evaluated at parse time, they are available before its declaration at runtime.

    See also:

    • Named function expressions demystified (article)
    • Explain JavaScript’s encapsulated anonymous function syntax
    0 讨论(0)
  • 2020-12-06 07:46

    The first one is a function expression,

    var calculateSum = function(a, b) { return a + b; }
    
    alert(calculateSum(5, 5)); // Alerts 10
    

    The second one is a plain function declaration.

    0 讨论(0)
  • 2020-12-06 07:49

    The function declaration syntax cannot be used within a block statement.

    Legal:

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

    Illegal:

    function a() {
        if (c) {
            function b() {
    
            }
        }
    }
    

    You can do this though:

    function a() {
        var b;
        if (c) {
            b = function() {
    
            };
        }
    }
    
    0 讨论(0)
  • 2020-12-06 07:57
    function myFunction() {}
    

    ...is called a "function declaration".

    var myFunction = function() {};
    

    ...is called a "function expression".

    They're very similar; however:

    • The function declaration can be declared after it is referenced, whereas the function expression must be declared before it is referenced:

      // OK
      myFunction();
      function myFunction() {}
      
      // Error
      myFunction();
      var myFunction = function() {};
      
    • Since a function expression is a statement, it should be followed by a semi-colon.

    See Function constructor vs. function declaration vs. function expression at the Mozilla Developer Centre for more information.

    0 讨论(0)
提交回复
热议问题