美文网首页
javascript变量和function作用域提升

javascript变量和function作用域提升

作者: z_love | 来源:发表于2021-01-13 23:58 被阅读0次
    console.log(a) // undefined
    console.log(b) // b is not defined
    test() // test
    console.log(test2) // undefined
    var a = '1'
    function test() {
        console.log('test')
    }
    var test2 = function() {
        console.log('test2')
    }
    

    分析

    • var定义的变量,声明会提前最前面,所以a输出的结果是undefined
    • 未声明的变量b会直接报错
    • function中声明和赋值都会作用域提升到最前面,所有test函数有值,可以执行
    • test2实际上是var声明变量,所以打印的是undefined,和a变量是一样的,并不会因为是匿名function而作用域提升

    相关文章

      网友评论

          本文标题:javascript变量和function作用域提升

          本文链接:https://www.haomeiwen.com/subject/pylmaktx.html