我试着忍受这个javascript代码但厌倦了吗?

时间:2016-11-26 18:03:24

标签: javascript html5

    <!DOCTYPE html>
    <html>
    <body onload="myFunction()">
    <script>
    var go="globle";
    function myFunction() {
    var go="local";
    document.write(go);
         }
    document.write(go);
    </script>

    </body>
    </html>

当我运行此代码时,它将打印local.But当我运行以下代码时:

    <!DOCTYPE html>
    <html>
    <body onload="myFunction()">
    <script>
    var go="globle";
    function myFunction() {
    var go="local";
        }
    document.write(go);
    </script>

    </body>
    </html>

此代码打印全球。 为什么不在第一个代码打印本地和全球。 而且当我运行第一个代码时,我的html主体也没有被执行。

2 个答案:

答案 0 :(得分:1)

您正在使用document.write,它会在调用时删除所有内容。

  

write()方法主要用于测试:如果在a之后使用它   HTML文档已完全加载,它将删除所有现有的HTML。

将其更改为console.log(go),您将看到预期的输出。

答案 1 :(得分:1)

由于使用document.write,您的第一个示例存在缺陷。当您在构建文档之后使用该文档时,它将清除早期文档并写入新文档。你在第一个例子中看到的结果被这个扭曲了。

实际上,您的示例只是在JavaScript中展示全局与功能范围。在函数中使用var声明的任何内容都具有该函数的局部作用域,并且当声明它的函数终止或不再保留在内存中时,将从内存中删除。

查看我已添加到您稍加修改的代码中的评论:

&#13;
&#13;
// We are going to replace all the document.write() calls with
// console.log() calls because you are experiencing information being
// written to the document and then the document is being overwritten 
// with new information.

// The result will be "global, local" because the code in "myFunction" is
// not going to run until the window is loaded. The last line of code in 
// this example will actually run first.
window.onload = myFunction;

var go="global";  // Just declare a Global variable (available everywhere)

function myFunction() {
    // Declare a local variable, available only in the function
    // Since this variable uses the same name as the global one
    // when this function is executing, this variable will override
    // (hide) the other one.
    var go= "local";  
  
   console.log(go);  // The local one is used
}

// Now, we are outside the function and the local version of "go" is 
// out of scope. It's gone and can't be accessed. But, the global version
// is still available
console.log(go);  // The global one is used
&#13;
&#13;
&#13;

这是你的第二个例子:

&#13;
&#13;
// Again, we're replacing document.write with console.log

// Even though we're calling the "myFunction" function when the
// window is loaded, that function only sets a local variable
// that will be destroyed when the function ends. It never does
// anything with that variable.
window.onload = myFunction;

var go="global";

function myFunction() {
    // This will be destroyed as soon as the function is done
    // which is the line right after it gets declared!
    var go="local";  
}

// Again, the scope of this line of code is global and so the global value is used
console.log(go);
&#13;
&#13;
&#13;