首页 > 网站 > WEB开发 > 正文

JS闭包

2024-04-27 14:06:31
字体:
来源:转载
供稿:网友

JS闭包

一、闭包的概念:

闭包是一个拥有许多变量和绑定了这些变量的环境的表达式(通常是一个函数),因此这些变量也是该表达式的一部分。用通俗的话来说,JS中的所有function都是一个闭包,但嵌套的function产生的闭包更为强大,这也是大部分时候我们所谓的闭包。

二、闭包的微观世界:

要深入理解闭包以及函数a和嵌套函数b的关系,我们需要了解函数执行环境(excution content)、活动对象(call object)、作用域(scope)和作用域链(scope chain)的概念。以函数a从定义到执行的过程为例来阐述这几个概念:

当定义函数a的时候,JS解释器会将函数a的作用域链设置为“定义a时a所在的环境”,如果a是一个全局函数,则作用域链中只有window对象;

当执行函数a时,a会进入相应的执行环境;

在创建执行环境的过程中,首先会为函数啊添加一个scope属性,即a的作用域,其值就是第一步中的作用域链,即a.scope=a的作用域链;

然后执行环境会创建一个活动对象。活动对象也拥有一个属性对象,但它不具有原型而且不能通过javaScript直接访问。创建完活动对象后,把活动对象添加到a的作用域链的最顶端。此时a的作用域链包含两个对象:a的活动对象和window对象;

下一步是在活动对象上添加一个arguments属性,它保存着调用函数a时所传递的参数。

最后把所有函数a的形参和内部的函数b的引用也添加到a的活动对象上。在这一步中,完成了函数b的定义,因此如同第三步,函数b的作用域链被设置为b所被定义的环境,即a的作用域。

到此,整个函数a从定义到执行的步骤就完成了。此时a返回函数b的引用给c,又函数b的作用域链包含了对函数a的活动对象的引用,也就是说b可以访问到a中定义的所有变量和函数。函数b被c引用,函数b有依赖于函数a,因此函数a在返回后不会被GC收购。

QQS2P1QqVT/93//p/rZz37W2Ngo2OdwOLalTQkkkEACCcQDlUplt9tVCZs9gQQSeJWxvLy83U3YSHyr7O+8805C2RNIIIEEVl4Kd8V3NntTU5MjhJWVFUcCCSSQQAK7E98pe2Nj43Y3JoEEEkgggQ1AQtkTSCCBBBzT09M1NTXNzc20Ba6Ltra2trY2h8Nx//79bWtc9Ego+6sOnueV57Hb7Xa7nf4ODQ1FP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