Estoy leyendo un artículo (JavaScript Closures for Dummies) y uno de los ejemplos es el siguiente.¿Cómo se hace referencia a las variables locales en los cierres?
function buildList(list) {
var result = [];
for (var i = 0; i < list.length; i++) {
var item = 'item' + list[i];
result.push(function() {alert(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]();
}
}
testList();
Cuando LISTAPRUEBA se llama, un cuadro de alerta que dice "elemento3 indefinido". El artículo tiene esta explicación:
Cuando las funciones anónimas son llamados en la línea
fnlist[j]();
todos utilizan el mismo cierre sola, y que utilizan el valor actual de I y el tema dentro de ese un cierre (donde i tiene un valor de 3 porque el ciclo se completó, y el elemento tiene un valor de 'elemento 3').
¿Por qué el artículo tiene un valor de 'item3'? ¿No termina el bucle for cuando llego a 3? Si termina, ¿no debería el elemento seguir siendo 'item2'? ¿O es el elemento variable creado de nuevo cuando testList llama a las funciones?
se trata de un error que hace más texto que pretende estar vinculado? – CookieOfFortune