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

99
Vistas
Prevent Stringifcation of Objects Passed Into Eval

Consider this code:

function set(n,v) {  // This is a setter
    eval(n+"="+v);
}

let one = 1;
function add1(num) {
    return num + one;
}

{
    let two = 2;
    set("add1", function(num) {
        return num + two;
    });

}

// Add 1 now equals: 
//  function(num) {
//      return num + two;
//  }

// So if we call add 1:
add1();

// We get a "Uncaught ReferenceError: two is not defined"

This is because eval stringifies the function which removes its connection to variables it counts on

How do I stop this (keep the set behavior, but prevent the function from leaving behind variables)

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

0

DON'T USE eval for variable variables. Use objects instead, as explained here

Now, to answer your question: as a direct eval can access your local variables, all you have to do is read them inside the eval string, instead of passing from the outside:

function set(n, v) {
    eval(n + "= v");
}
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