开发者

What is the difference between these two functions/approaches?

开发者 https://www.devze.com 2022-12-19 00:15 出处:网络
I use only jQuery for writing JavaScript code. One thing that confuses me is these two approaches of writing functions,

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

First approach

vote = function (开发者_如何学JAVAaction,feedbackId,responseDiv)
{
    alert('hi');
    return feedbackId;
}

Second approach

function vote(action, feedbackId,responseDiv)
{
    alert('hi');
    return feedbackId;
}

What is the difference between the two and why should one use the first approach or the second approach?


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


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.


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() {

        };
    }
}


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

精彩评论

暂无评论...
验证码 换一张
取 消