在方法b()
在document.writeln(x)后,是否写var x='bbb';会有很大的差别   为什么会产生这种情况呢?
等高人

解决方案 »

  1.   

    var x = 123;function a() {
    alert(x); // 123
    }function b() {
    alert(x); // undefined
    alert(window.x); // 123
    var x = 456;
    }
    a(); 
    b();简单来说:在函数中声明了同名局部变量那么全局变量就失效了。
      

  2.   

    var x = 123;
    function a() {
        alert(x); // 123
    }
    function b() {
       
    alert(x); // 这样就弹出123 晕~
        alert(window.x); // 123
        //var x = 456;<<<<<<<<<<<<
    }
    a(); 
    b();var x = 123;
    function a() {
        alert(x); // 123
    }
    function b() {
        var x=789
    alert(x); // 这样就弹出789 晕~
        alert(window.x); // 123
        //var x = 456;<<<<<<<<<<<<
    }
    a(); 
    b();alert(a)//undefined
    var a="ss"alert(a)//undefined
    var a=function(){}alert(a)//弹出 function a(){}
    function a(){}alert(a)//不加var 会报错
    a="ss"alert(b)//不加var 会报错
    b=function(){}b=function(){}//放在前面就不一样
    alert(b)//弹出function(){}总结一下:function a(){}这样会先执行  var 的变量或函数 出现在后面 在前面调用 会显示undefined 
    如果前面调用后面的变量 后面的变量不加 var 就报错 
    自己感觉:系统会先把var了的变量名提取出来 以备比对 但不能赋予 
      

  3.   

    var x='000';   
    document.writeln(x);//000   
    a()
    function a(){   
     function b(){   
      document.writeln(x);//111   
      document.writeln(x);//111   
     }   
     document.writeln(x);//undefined  
     var x='111';   
     b();;    
    }   
    //弹出000 undefined 111 111
      

  4.   

    写个简单的测试下就行了<script>
    var x='outer_X'; //声明一个全局的test(); // undefined
    function test(){
    alert(x); // 这里的x值为undefined
    var x = 'inner_x';
    }
    </script>
      

  5.   

    var x=100
    document.writeln(x)
    add(x)
    document.writeln('</br>------------------------</br>')
    var x=200
    document.writeln(x)
    add(x)
    function add(x){
        document.writeln(x)
        var x=300
        document.writeln(x)    
        var x=400
        document.writeln(x)   
    }100 100 300 400 
    ------------------------ 
    200 200 300 400 
      

  6.   

    Do not use the write method or the writeln method on the current document after the document has finished loading unless you first call the open method, which clears the current document window and erases all variables.执行writeln后,其他的内容就清除了,所以x不存在了
      

  7.   

    方法因为是在解析中执行的, 应该不存在清除一说这和变更的声明及作用域有关6#里有个例子, 另再举一例, 结合JS作用域不难理解...<script>
    alert(x); // undefined, 如果下面没有 声明x变更, 这里会报错`
    var x = 1;
    </script>