Scope Chain & Closure

我们先来小试身手,在这之前我们必须有function scope 跟 global varible的基本知识


let a = "hello"function test1(){    var a = "Goodbye"    console.log(a) // Goodbye    test2() }function test2(){        console.log(a) //hello}test1()

首先我们在全域定义 a = "hello",在function test1里面又定义一次 a = "Goodbye",想当然尔function scope
就会输出Goodbye,并且function test1 callback function test2,但是test2并没有定义a ,那就会变成从全域变数找有没有a的数值,并且找到 a = "hello!!!


接下来让我们把function 改的複杂一点

let a = "Dennis"function test1(){    var a = "Jessica"    console.log(a) //Jessica    function test2(){        console.log(a) //Jessica    }    function test3(){        var a = "Jack"        console.log(a) //Jack        test2()    }    test3()}test1()

首先看到test1是一个function scope,定义 a = "Jessica"并且里面有两个function,function test3 call function test2,但function test3定义 a = "Jack",所以function test3会输出"Jack",但是function test2 是function test1里面的所以会抓取function test1的 a,最后输出 "Jessica"


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章