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元素獲取其indexjavascript

 

相關資料:html

阮一峯的網絡日誌 http://www.ruanyifeng.com/blog/2009/08/learning_javascript_closures.htmljava

酷殼 http://coolshell.cn/articles/6731.htmlgit

stackoverflow http://stackoverflow.com/questions/111102/how-do-javascript-closures-workgithub

mdn https://developer.mozilla.org/zh-CN/docs/JavaScript/Guide/Closuresshell

爲之漫筆 http://www.cn-cuckoo.com/main/wp-content/uploads/2007/08/JavaScriptClosures.html網絡

相關文章
相關標籤/搜索