Ambiguous function declaration in Javascript

前端 未结 4 1285
面向向阳花
面向向阳花 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 00:48

    Javascript works like this:

    The document is parsed, and the function declarations are all taken taken into account immediately, before the execution of the actual statements occur. This explains your first example.

    If you assign a function to a local variable, that is done during the execution, so you can't use the method in your second example.

    What you experience is that if you declare a function twice, the last one will be used by the entire application. That's your third example.

    These functions are made members of the window object, they are in effect declared globally. If you assign a local variable to a value of a function, then that local variable takes precedence over members in the window object. If javascript can't find a local variable, it searches up in scope to find it, the window object being the last resort. That's what happened in your last example, it has a variable say that is in a more specific scope than the global function say.

    If you would redeclare say at runtime, i.e. swap the order of declarations in your last example, then you would see the two different alerts you'd expect:

    say(); //speak, the global function
    
    function say() {
      alert('speak');
    }
    
    var say = function() {
      alert('say');
    }
    
    say(); //say, the declared local variable
    

提交回复
热议问题