Are function arguments stored in a closure?
Posted
by Nick Lowman
on Stack Overflow
See other posts from Stack Overflow
or by Nick Lowman
Published on 2010-05-19T13:15:02Z
Indexed on
2010/05/19
13:30 UTC
Read the original article
Hit count: 138
JavaScript
I was reading this great article about closures here and the example below outputs 'item3 undefined' three times.
I understand why it outputs 'item3' three times as the functions inside buildList() all use the same single closure but why can't it access the 'list' argument? Why is it undefined? Is it because the argument is passed in after the closure has been created?
function buildList(list) {
var result = [];
for (var i = 0; i < list.length; i++) {
var item = 'item' + list[i];
result.push( function() {console.log(item + ' ' + list[i])} );
}
return result;
}
function testList() {
var fnlist = buildList([1,2,3]);
// using j only to help prevent confusion - could use i
for (var j = 0; j < fnlist.length; j++) {
fnlist[j]();
}
}
© Stack Overflow or respective owner