Skip to content

Instantly share code, notes, and snippets.

@overminder
Last active August 29, 2015 14:06
Show Gist options
  • Save overminder/0c783040a5999a58096b to your computer and use it in GitHub Desktop.
Save overminder/0c783040a5999a58096b to your computer and use it in GitHub Desktop.
见 http://h.acfun.tv/t/4240594?r=4256785
// 要注意 JS 里,closure 的值的确是有些奇怪的地方,像这样写就会出问题:
function mkClosures() {
var xs = [];
for (var i = 0; i < 10; ++i) {
xs.push(function() { console.log(i); });
}
return xs;
}
var cs = mkClosures();
for (var i = 0; i < cs.length; ++i) {
cs[i]();
}
// 看起来会 log 出 0-9,但是实际上都是 10。你可以认为 closure 里存着的是同一个 i。
//
// 那么怎么办呢?你可以这么写:
function mkClosure(i) {
return function() {
console.log(i);
}
}
function mkClosures() {
var xs = [];
for (var i = 0; i < 10; ++i) {
xs.push(mkClosure(i));
}
return xs;
}
var cs = mkClosures();
for (var i = 0; i < cs.length; ++i) {
cs[i]();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment