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)