Angular中使用new Function调用嵌套函数报错求助
解决new Function中无法访问嵌套函数的问题
你遇到的问题是因为testFunc执行后默认返回undefined,所以调用testFunc().nestFunc2()时找不到嵌套函数。要让脚本能访问到嵌套函数,需要让testFunc返回一个包含这些嵌套函数的对象,同时保留原有的逻辑。
修改后的代码如下:
test() { const script = ` var value = 1 +4; console.log('value',value); testFunc('Success'); testFunc().nestFunc2(); console.log("End Script"); `; var testFunc = (msg?: string) => { // 保留原有的日志逻辑 if (msg !== undefined) { console.log('Test Function', msg); } // 返回包含嵌套函数的对象 return { nestFunc1: () => { alert('hi'); }, nestFunc2: () => { alert('hi'); } }; }; const userFunction = new Function('testFunc', script); userFunction(testFunc); }
这样修改后,testFunc()会返回包含nestFunc1和nestFunc2的对象,脚本里就能正常调用testFunc().nestFunc2()了。同时testFunc('Success')也能正常执行日志输出。
内容的提问来源于stack exchange,提问作者Ka Tech
相关产品推荐
相关产品推荐

