Difference between Javascript function declarations

以下两个例子有什么区别?

setInterval(myFunc, 100);

function myFunc() { alert('asdf'); } 

setInterval(myFunc, 100);

var myFunc = function myFunc() { alert('asdf'); }

According to ECMA standard, the first example is a function statement while the second is a function expression. According to Javascript a function statement counts as a definition, which means in the first example it is visible through the entire function (or script if it's not in a function). But in the second example, var myFunc will not have the value of function myFunc until the second line, and therefore setInterval will be passed undefined .

The only syntax difference between function statements and expressions is that statements are not included in are larger expression: eg: (function foo() {}) is an expression, while function foo() {} is a statement.

NB: I believe old IE (pre 9?) treated all function expressions as definitions.

To expound on this answer, consider the following code:

    <script language="javascript">
        alert(A);
        alert(B);
        function A() {return "A value";}
        var B = function B(){ return "B value";}

        alert(A);
        alert(B);
    </script>

this will alert (in order):

  • Function A()...
  • undefined
  • Function A()...
  • Function B()...

  • Both samples are essentially doing the same thing. In the second example, you can also use a named function with a different name or an unnamed function.

    var myFunc = function myOtherName() { alert('asdf'); }
    

    or

    var myFunc = function() { alert('asdf'); }
    

    They are all the same.


    In the first example:

    > setInterval(myFunc, 100);
    > 
    > function myFunc() { alert('asdf'); }
    

    The function declaration is processed before any code is executed, so myFunc exists as a local parameter when setInterval is called.

    The second example:

    > setInterval(myFunc, 100);
    > 
    > var myFunc = function myFunc() {
    > alert('asdf'); }
    

    works for exactly the same reason: myFunc is declared using var and therefore exists as a local variable when setInterval is called.

    Edit

    Ooops! It doesn't work. The value of myFunc is evaluated when setTimeout is called, and at that point myFunc hasn't bee assigned a value so an error results. Changing the value later doesn't affect the value held by setTimeout.

    Finally, there is no such thing as a "function statement". ECMA-262 defines FunctionDeclaration and FunctionExpression in §13, there is no other kind of function.

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

    上一篇: 变量提升

    下一篇: Javascript函数声明之间的区别