本文实例讲述了javascript中的闭包概念与用法。分享给大家供大家参考,具体如下:
闭包的概念:闭包是指有权访问另一个函数作用域中的变量的函数 (引自《javascript高级程序设计第三版》178页)。闭包的优点是不会产生全局变量,避免变量污染问题,但是闭包也有一个缺点就是闭包携带包含它的函数作用域会比其它函数占用更多的内存,过度使用会导致内存占用过多。
wiki上关于闭包的概念:
In programming languages, closures (also lexical closures or function closures) are techniques for implementing lexically scoped name binding in languages with first-class functions. Operationally, a closure is a record storing a function[a] together with an environment:[1] a mapping associating each free variable of the function (variables that are used locally, but defined in an enclosing scope) with the value or reference to which the name was bound when the closure was created.[b] A closure—unlike a plain function—allows the function to access those captured variables through the closure's copies of their values or references, even when the function is invoked outside their scope.
简单来说:闭包是一个存储了函数以及与这个函数相关的环境信息的记录。
闭包实践一:初次体验闭包
function a() { var temp = 100; function b() { console.log(++temp); } return b;}var fn = a(); // 此时fn属于全局的函数。fn();// 101fn();// 102
在函数a的内部return出了一个局部函数b。让函数fn接收函数a的返回值,也就是函数b。连续执行了两次fn,输出结果101,,102表示,函数fn一直引用着函数a中的局部变量temp。每次调用fn,temp都会被自增1。从此处说明了函数a一直没有被垃圾回收机制(GC)回收。以上代码还可以这样优化:
function a() { var temp = 100; return function() { console.log(++temp); }}var fn = a();a = null;fn();// 101fn();// 102fn = null; // 调用完毕后要,要解除对内部匿名函数的引用,以便释放内存
闭包实践二:闭包与变量
分析下面的代码
html结构:
<ul> <li>0</li> <li>1</li> <li>2</li></ul>
javascript结构:
var ul = document.querySelector('ul');// 为了演示方便,直接用html5的apivar lis = ul.children;for(var i=0; i< lis.length; i++) { lis[i].οnclick=function(){ console.log(i); }}
当点击每个li时,输出的全都是3,在点击事件之前,for循环早已经执行完了,i的值为3。为了防止这种情况发生,for循环还可以修改成这样:
for(var i=0; i< lis.length; i++) { lis[i].οnclick=function(num){ return function(){ console.log(num); } }(i)}
新闻热点
疑难解答
图片精选