var btns = document.getElementsByTagName('button') for (var i = 0,length=btns.length; i < length; i++) { var btn = btns[i] //将btn所对应的下标保存在btn上 btn.index = i btn.onclick = function () { alert('第'+(this.index+1)+'个') } } //利用闭包 for (var i = 0,length=btns.length; i < length; i++) { (function (j) { var btn = btns[j] btn.onclick = function () { alert('第'+(j+1)+'个') } })(i) }
function fn1() { var a = 2; function fn2() { a++; console.log(a); } return fn2; } var f = fn1(); f(); f();
function showDelay(msg, time) { setTimeout(function () { alert(msg) }, time) } showDelay('atguigu', 2000)
f = null
(function (window) { //私有的数据 var msg = 'atguigu' var names = ['I', 'Love', 'you'] //操作数据的函数 function a() { console.log(msg.toUpperCase()) } function b() { console.log(names.join(' ')) } window.coolModule2 = { doSomething: a, doOtherthing: b }
})(window)
* 循环遍历加监听 * JS框架(jQuery)大量使用了闭包 * 缺点: * 变量占用内存的时间可能会过长 * 可能导致内存泄露 * 解决: * 及时释放 : f = null; //让内部函数对象成为垃圾对象 ************* ## 面试题 * 1. ```js //代码片段一 var name = "The Window"; var object = { name : "My Object", getNameFunc : function(){ return function(){ return this.name; }; } }; alert(object.getNameFunc()()); //? the window //代码片段二 var name2 = "The Window"; var object2 = { name2 : "My Object", getNameFunc : function(){ var that = this; return function(){ return that.name2; }; } }; alert(object2.getNameFunc()()); //? my object
function fun(n,o) { console.log(o) return { fun:function(m){ return fun(m,n) } } } var a = fun(0) a.fun(1) a.fun(2) a.fun(3)//undefined,0,0,0 var b = fun(0).fun(1).fun(2).fun(3)//undefined,0,1,2 var c = fun(0).fun(1) c.fun(2) c.fun(3)//undefined,0,1,1
// 1. 内存溢出 var obj = {} for (var i = 0; i < 10000; i++) { obj[i] = new Array(10000000) console.log('-----') } // 2. 内存泄露 // 意外的全局变量 function fn() { a = new Array(10000000) console.log(a) } fn() // 没有及时清理的计时器或回调函数 var intervalId = setInterval(function () { //启动循环定时器后不清理 console.log('----') }, 1000) // clearInterval(intervalId) // 闭包 function fn1() { var a = 4 function fn2() { console.log(++a) } return fn2 } var f = fn1() f() // f = null