Last active
August 29, 2015 14:12
-
-
Save cheng470/1703ae26acf3bb996bd7 to your computer and use it in GitHub Desktop.
使用立即调用的函数表达式创建局部作用域
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function wrapElements(a) { | |
var result = [], i, n; | |
for (i = 0, n = a.length; i < n; i++) { | |
result[i] = function() { return a[i]; }; | |
} | |
return result; | |
} | |
var wrapped = wrapElements([10, 20, 30, 40, 50]); | |
var f = wrapped[0]; | |
f(); // ? |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function wrapElements(a) { | |
var result = [], i, n; | |
for (i = 0, n = a.length; i < n; i++) { | |
(function() { | |
var j = i; | |
result[i] = function() { return a[j]; }; | |
})(); | |
} | |
return result; | |
} | |
function wrapElements(a) { | |
var result = [], i, n; | |
for (i = 0, n = a.length; i < n; i++) { | |
(function(j) { | |
result[i] = function() { return a[j]; }; | |
})(i); | |
} | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment