JavaScript-变量作用域

在 JavaScript 中定义变量有两种方式

ES6 之前: var 变量名称;
ES6 开始: let 变量名称;

两种定义变量方式的区别

如果通过 var 定义变量, 可以重复定义同名的变量, 并且不会报错, 并且后定义的会覆盖先定义的。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Demo</title>
    <script type="text/javascript">
        var num = 123;
        var num = 456;
        console.log(num);
    </script>
</head>
<body>
</body>
</html>

如果通过 var 定义变量, 可以先使用后定义 (预解析)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Demo</title>
    <script type="text/javascript">
        console.log(num);
        var num = 123;

        // 如上代码等价于下面代码

        // var num;
        // console.log(num);
        // num = 123;
    </script>
</head>
<body>
</body>
</html>

如果通过 let 定义变量, 不可以重复定义同名的变量。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Demo</title>
    <script type="text/javascript">
        let num = 123;
        let num = 456;

        console.log(num);
    </script>
</head>
<body>
</body>
</html>

如果通过 let 定义变量, 不可以先使用再定义, 因为浏览器不会对 let 定义的变量进行 预解析

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Demo</title>
    <script type="text/javascript">
        console.log(num);
        
        let num = 123;
    </script>
</head>
<body>
</body>
</html>

无论是通过 var 还是通过 let 定义的全局变量, 都是从定义的那一行到文件末尾都可以使用。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Demo</title>
    <script type="text/javascript">
        // 全局变量

        var numOne = 123;

        let numTwo = 123;
    </script>
</head>
<body>
</body>
</html>
<script>
    console.log(numOne);
    console.log(numTwo);
</script>

如果是通过 var 定义的 局部变量, 和全局变量一样, 后续都可以被使用。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Demo</title>
    <script type="text/javascript">
        // 局部变量
        {
            var num = 666;
            console.log(num);
        }

        console.log(num);

        if (true) {
            console.log(num);
        }
    </script>
</head>
<body>
</body>
</html>

如果是通过 let 定义的 局部变量, 那么这个变量只能在当前定义变量的 {} 中使用。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Demo</title>
    <script type="text/javascript">
        // 局部变量
        {
            let num = 666;
            console.log(num);
        }
        
        console.log(num);
        
        if (true) {
            console.log(num);
        }
    </script>
</head>
<body>
</body>
</html>

posted @ 2021-06-29 15:28  BNTang  阅读(51)  评论(0编辑  收藏  举报