【发布时间】:2022-01-05 20:19:36
【问题描述】:
闭包值在作为回调传递给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
【问题讨论】:
标签: javascript function callback closures uncaught-reference-error