闭包值在作为回调传递给由方法定义的另一个函数的函数中丢失。new Function()
代码
如何baz()
修复函数以访问回调中的闭包值?
注意:该功能foo()
不可修改。
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