0

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)

Bagel03
  • 725
  • 7
  • 22

1 Answers1

2

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");
}
FZs
  • 16,581
  • 13
  • 41
  • 50