声明提前(hoist)

版权声明:如有文章想转载请联系qq:1289281445 tel:13253311994 https://blog.csdn.net/qq_39458856/article/details/82385323

WHAT

在程序正式执行之前,先将var声明的变量和function声明的函数提前到当前作用域的顶部,

集中创建

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>$Title$</title>
</head>
<body>
<script >
    function fun() {
        console.log("1")
    }
    fun()
    function fun() {
        console.log("2")
    }
    fun()
</script>
</body>
</html>

以上例子中的函数会被提前,后创建的同名函数会覆盖之前的函数

解决声明提前:

1.赋值:var 函数名=function(参数列表){

                  函数体;

                  return 返回值

}

why:在声明提前时只会将两个函数的名字提前,其中的内容不变,留在原地

    var fun2=function () {
        console.log("3")
    }
    fun2()
    var fun2=function () {
        console.log("4")
    }
    fun2()

function为一个动词代表function

创建函数:1.function fun(){}

                  2.new Function("变量1","变量2","return ..")

猜你喜欢

转载自blog.csdn.net/qq_39458856/article/details/82385323