Javascript local and global variable confusion

This question already has an answer here:

  • How do JavaScript closures work? 88 answers
  • Variable: local scope, global scope or is it the JavaScript engine? 3 answers

  • In Javascript, the variable declarations are automatically moved to the top of the function. So, the interpreter would make it look more like this:

    var myname = "initial"
    function c(){
        var myname;
        // alerts undefined
        alert(myname);
        myname = "changed";
        // alerts changed
        alert(myname);
    }
    c();
    

    This is called 'hoisting'.

    Due to hoisting and the fact that the scope for any variable is the function it's declared in, it's standard practice to list all variables at the top of a function to avoid this confusion.


    It is not replace the global variable. What is happening is called "variable hoisting". That is, var myname; gets inserted at the top of the function. Always initialize your variables before you use them - try this:

    var myname = "initial";
    
    function c() {
        alert(myname);
        myname = "changed";
        alert(myname);
    }
    
    c();
    链接地址: http://www.djcxy.com/p/1470.html

    上一篇: 执行JavaScript代码的尴尬方式

    下一篇: Javascript本地和全局变量混淆