javascript作用域和作用域链

<!DOCTYPE html>

<html>

<head>

    <meta charset="UTF-8">

    <title>test</title>

</head>

<body>

    <script>

        window.onload=function(){

            var scope="global";

            function t(){

                console.log(scope);

                var scope="local";

                console.log(scope);

            }

            t();

        }

    </script>

</body>

</html>

上面的这一段代码,第一个打印的是undefined,第二个打印的是local,这是为什么啊,不是说通过作用域链可以向上访问的吗,那为什么第一次打印的时候会是undefined。

holdtom
浏览 465回答 1
1回答

慕神8447489

不知道你看的哪本书,应该基本上都会讲到。window.onload=function(){&nbsp; &nbsp; var scope="global";&nbsp; &nbsp; &nbsp; &nbsp; function t(){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(scope);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var scope="local";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(scope);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; t();}这里是变量声明提前,修改后就是这样&nbsp; &nbsp; &nbsp; &nbsp; function t(){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var scope;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(scope);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; scope = "local";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(scope);&nbsp; &nbsp; &nbsp; &nbsp; }所以第一个.log输出是因为在自己的函数作用域链上找到了一个本地变量,但是此时还没有赋值-->undefined。同理,第二个是因为已经赋值了--> local。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript