js作用域链的简单理解

    技术2022-07-13  85

    阅读本段代码,写出打印结果

    let a = 10 let c = 10 let b = 10 function fun() { let b = 20 fn() function fn() { let a = 5 console.log(a) //a=? console.log(b) //b=? console.log(c) //c=? } } fun() //执行fun 问 a = ? , b = ? , c=?

    对该代码的分析:

    全局作用域下:function fun() , let a =10 , let b = 10 , let c = 10。 fun函数作用域下:function fn(),let b = 20。 fn函数作用域下:let a = 5。 console.log(a),fn作用域下开始找a,很幸运在本作用域下找到了a=5 console.log(b),fn作用域下没有b,便沿着作用域链往上来到fun作用域,找到了 b = 20 console.log(c),fn作用域没有c,,往上找来到fun作用域没有c,再往上来到全局作用域下找到c = 10

    对该代码的图解:

    总结一句话: 从输出位置开始往上找,最先找到的就是你要的结果了

    Processed: 0.008, SQL: 9