JS经典闭包问题
1 // 转载自: https://gist.github.com/iwillwen/8732729 2 3 'use strict'; 4 5 var arr = [ 1, 2, 3, 4, 5 ]; 6 var fnArr = []; 7 8 // Wrong 1 9 for (var i = 0; i < arr.length; i++) { 10 fnArr[i] = function() { 11 return arr[i]; 12 }; 13 } 14 15 fnArr.forEach(function(fn) { 16 console.log(fn()); 17 }); 18 // undefined * 5 19 20 // Wrong 2 21 for (var i = 0; i < arr.length; i++) { 22 var curr = arr[i]; 23 fnArr[i] = function() { 24 return curr; 25 }; 26 } 27 28 fnArr.forEach(function(fn) { 29 console.log(fn()); 30 }); 31 // 5 * 5 32 33 // Solution 1 34 for (var i = 0; i < arr.length; i++) { 35 fnArr[i] = (function(ii) { 36 return function() { 37 return arr[ii]; 38 }; 39 })(i); 40 } 41 42 fnArr.forEach(function(fn) { 43 console.log(fn()); 44 }); 45 // 1 2 3 4 5 46 47 // Solution 2 - ECMAScript 5 48 arr.forEach(function(row, i) { 49 fnArr[i] = function() { 50 return row; 51 }; 52 }); 53 54 fnArr.forEach(function(fn) { 55 console.log(fn()); 56 }); 57 // 1 2 3 4 5 58 59 // Solution 3 - Harmony 60 for (var i = 0; i < arr.length; i++) { 61 let curr = arr[i]; 62 fnArr[i] = function() { 63 return curr; 64 }; 65 } 66 fnArr.forEach(function(fn) { 67 console.log(fn()); 68 }); 69 // 1 2 3 4 5
实际中可能遇到的类似问题是: 点击li元素获取其index
相关资料:
阮一峰的网络日志 http://www.ruanyifeng.com/blog/2009/08/learning_javascript_closures.html
酷壳 http://coolshell.cn/articles/6731.html
stackoverflow http://stackoverflow.com/questions/111102/how-do-javascript-closures-work
mdn https://developer.mozilla.org/zh-CN/docs/JavaScript/Guide/Closures
为之漫笔 http://www.cn-cuckoo.com/main/wp-content/uploads/2007/08/JavaScriptClosures.html