JavaScript 中变量声明提升机制

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JavaScript no.1</title>
</head>
<body>
    <h3>变量声明提升和函数内变量声明提升实例</h3>
    <script>
        if (a in window) {
            console.log('a已经存在');//结果输出a已经存在
        };
        var a=1;//变量声明提升

        (function()
        {
            console.log(a);//函数内变量声明提升且覆盖函数外的同名变量,输出 undefined
            var a=2;
        })();
    </script>
</body>
</html>

在JavaScript中所有在作用域中声明的变量会自动提升到该作用域的顶部

评论

暂无评论