Skip to content

Instantly share code, notes, and snippets.

@cheng470
Last active August 29, 2015 14:12
Show Gist options
  • Save cheng470/1703ae26acf3bb996bd7 to your computer and use it in GitHub Desktop.
Save cheng470/1703ae26acf3bb996bd7 to your computer and use it in GitHub Desktop.
使用立即调用的函数表达式创建局部作用域
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(); // ?
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