Closure values get lost in a function passed as a callback to another function defined by new Function()
method.
Code
How can the function baz()
be fixed to access the closure values in the callback?
Note: The function foo()
cannot be modified.
const foo = () => {
const b = 2;
return (a) => {
return a + b; // unable to access `b` here
};
};
const bar = (a = 1, callback = foo()) => callback(a);
const baz = new Function(["a = 1", `callback = ${foo()}`], "return callback(a)");
console.log(bar(1)); // works fine and prints 3
console.log(baz(1)); // throws Uncaught ReferenceError: b is not defined