访问规则,就近原则


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        // 全局变量100
        var num = 100
        
        function test1(){
            var num = 200
            function child(){
                var num = 300
                console.log(num)
            }
            child()
        }
        test1()
    </script>
</body>
</html>
 
就近原则 num 等于100

<script>
        // 全局变量100
        var num = 100
        function test1(){
            var num = 200
            function child(){
                // var num = 300
                console.log(num)
            }
            child()
        }
        test1()
    </script> 
num等于300的注释掉,往上找,所以num等于200
 
num=300和num = 200注释掉,在往上找,所以num等于100
 <script>
        // 全局变量100
        var num = 100
        function test1(){
            // var num = 200
            function child(){
                // var num = 300
                console.log(num)
            }
            child()
        }
        test1()
    </script> 

 赋值规则,就近原则
 
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        // 全局变量100
        // num值不改变
        var num = 100
        function test1(){
            // num值不改变
            var num = 200
            function child(){
                var num = 300
                // 只改变最近的num的值
                num = 400
                console.log(num)
            }
            child()
        }
        test1()
    </script>
</body>
</html>
 
 
<body>
    <script>
        // 全局变量100
        // num值不改变
        var num = 100
        function test1(){
            // num值变成400
            var num = 200
            function child(){
                // var num = 300
                // 只改变最近的num的值
                num = 400
                console.log(num)
            }
            console.log("修改前",num)
            child()
            console.log("修改后",num)
        }
        test1()
    </script>
 

特殊情况
赋值的时候往上找找到最外层都没找到,就把这个num=400变成全局变量
<script>
        // 全局变量100
        // num值不改变
        // var num = 100
        function test1(){
            // num值变成400
            // var num = 200
            function child(){
                // var num = 300
                // 只改变最近的num的值
                num = 400
                console.log(num)
            }
            // console.log("修改前",num)
            child()
            console.log("修改后",num)
        }
        test1()
    </script> 



















