Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

160
Vistas
I don't understand the example of closure for loop error from mdn

1.MDN example

The code snippet below assign a function that display the help text to each text field when focus, here is the link to JsFiddle: https://jsfiddle.net/v7gjv/8164/

function showHelp(help) {
          document.getElementById('help').textContent = help;
        }
        
        function setupHelp() {
          var helpText = [
              {'id': 'email', 'help': 'Your e-mail address'},
              {'id': 'name', 'help': 'Your full name'},
              {'id': 'age', 'help': 'Your age (you must be over 16)'}
            ];
        
          for (var i = 0; i < helpText.length; i++) {
            var item = helpText[i];
            document.getElementById(item.id).onfocus = function() {
              showHelp(item.help);
            }
          }
        }
        
        setupHelp();

But it will only display the last help text no matter which of the three input is focused. MDN says the function assigned to all three inputs is a closure, so they share the same reference to variable helpText, when the loop's over, i=2, so all three input have reference to the last item in helpText.

2.My test

The part where i dont understand is why all three inputs have the same reference to the same variable item I make a test like this

(function() {
  function closure() {
    var i = 0;
    return {
      display: function() {
        console.log(i);
      },
      add: function() {
        i += 1;
      }
    }
  }

  var a = closure();
  var b = closure();

  a.add();
  a.display(); //return 1
  b.display(); //return 0 
})()

3.My thoughts and questions

From the test, a and b have different i variables, i from a changed but b remain the same. But in the for loop, all inputs point to the same variable, thus the for loop change the value i causing all inputs point to the last item in helpText

So my question is why do they points to the same variable but in my test a,b don't.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

In your example, you're declaring the variable i inside the closure method. When you are calling closure a second time, a new i variable is created in the scope of that specific function execution, and the returned object is bound to that variable.

Try moving the variable declaration outside of the closure function and you will see that the result is the same as the MDN example.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda