Home  >  Q&A  >  body text

Problems with variables and functions with the same name

See the screenshot I took for detailsQQ截图20170620174114.jpg

phpcn_u3114phpcn_u31142700 days ago937

reply all(2)I'll reply

  • PHP中文网

    PHP中文网2017-06-21 09:38:13

    <script>
    var bar=function(){
       var foo=function(){}
       foo=10;
    }
    var foo=1;
    bar();
    alert(foo);
    </script>

    The js declaration part is placed on top, and the foo inside the function is a local variable and does not affect the global foo.

    reply
    0
  • phpcn_u3114

    Thank you for your answer, I figured it out

    phpcn_u3114 · 2017-06-21 22:38:15
    phpcn_u3114

    Thank you for your answer, I figured it out

    phpcn_u3114 · 2017-06-21 22:38:16
  • ringa_lee

    ringa_lee2017-06-21 09:37:34

    1 Function declaration will be at the top

    2 Variable declaration will also be at the top
    3 Function declaration will be at the top than variable declaration:)
    4 Variables and assignment statements are written together. When parsed by the js engine, they will be split into two parts: declaration and assignment. , the declaration is at the top, and the assignment remains at the original position
    5Declared variables will not be declared repeatedly

    If you refer to the above points, you will understand the reason!

    The actual effect of your code is:

    function bar(){
     function foo(){}
      var foo;//实际上无效
      foo=10;
    }
    var foo;
    bar();
    foo=1;
    console.log(foo);


    reply
    0
  • phpcn_u3114

    Thank you for helping me clear up my confusion. I figured it out.

    phpcn_u3114 · 2017-06-21 22:39:29
  • Cancelreply