Ambiguous function declaration in Javascript

前端 未结 4 1288
面向向阳花
面向向阳花 2020-12-19 00:10

I am new to Javascript and got confused by how the function declaration works. I made some test on that and got some interesting results:

say();

function sa         


        
4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-19 01:05

    say();
    
    function say()
    {
        alert("say");
    }
    

    Here the interpreter fetches the definition of say() when it is called, and executes it.

    say();
    
    say = function()
    {
        alert("say");
    }
    

    Here there is no definition of say() to fetch - instead you are assigning an anonymous function to a variable. The interpreter can't "find" this like it can find forward declarations.

    function say()
    {
        alert("speak");
    }
    
    say();
    
    function say()
    {
        alert("say");
    }
    

    Here say is defined and then redefined - the last definition wins out.

    say = function()
    {
        alert("speak");
    }
    
    say();
    
    function say()
    {
        alert("say");
    }
    
    say();
    

    Here say is a variable pointing to an anonymous function (after the first statement is interpreted). This takes precedence over any function definition, the same as if you had placed the function definition before the assignment.

    But if you had

    say();
    
    say = function()
    {
        alert("speak");
    }
    
    say();
    
    function say()
    {
        alert("say");
    }
    

    Then you would get "say" followed by "speak".

提交回复
热议问题