478 if里的函数声明

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        div {
            /*  200px; */
        }
    </style>
</head>

<body>

</body>

</html>
<script>
    /* 
    1).if里的函数声明首先会定义一个全局同名变量a = undefined
    2).if里的函数赋值会提升到块作用域顶部
    3).执行到函数声明语句时, 会把块作用域里的a赋值到全局同名变量a
    4).基于行为诡异,不同浏览器实现不同,建议在if里用函数表达式代替函数声明 
    */

    // 1、if里的函数声明,首先会定义一个全局同名变量 a = undefined
    console.log(window.a, a) // undefined  undefined

    if (true) {
        // 2、if里面的函数声明,首先会提升到块级作用域顶部
        console.log(window.a, a)  // undefined   f a() {}

        a = 6
        console.log(window.a, a)  // undefined  6

        a = 7
        console.log(window.a, a)  // undefined  7

        // 3、执行到函数声明语句时,会把块作用域的a赋值到全局同名变量 a
        function a() { }

        a = 8
        console.log(window.a, a)  // 7  8

        a = 9
        console.log(window.a, a)  // 7  9
    }

    console.log(window.a, a)  // 7  7

    
    // ----------------------------------------------


    // 后面的a = 1、a = 2都是改变块作用域里的a的值,所以a分别输出1  、2
    // 执行到function a() { },会把块作用域里的a赋值到全局同名变量a,即window.a = 2,所以后面的window.a 都是2,最后一行console.log(a),这个a是全局的,所以也是2

    var a = 0
    if (true) {
        console.log(window.a, a)  // 0  ƒ a() { }
        a = 1
        console.log(window.a, a)  // 0  1
        a = 2
        console.log(window.a, a)  // 0  2
        function a() { }
        console.log(window.a, a)  // 2  2
        a = 21
        console.log(window.a, a)  // 2  21
    }
    console.log(a)  // 2
</script>
原文地址:https://www.cnblogs.com/jianjie/p/13172330.html