JavaScript new Function scope ReferenceError

耗尽温柔 提交于 2020-02-02 08:16:25

问题


is there any way to make the code below working?

(function(){
    var n = "abc";
    (new Function("return alert(n);"))();
})();

If I run the code in browser result is: "Uncaught ReferenceError: n is not defined".

Also, I need to some other variables like "n" make accessible inside the "new Function" too.

Please help, Thank you


回答1:


So you need to make that variables global.

(function(){
    window.n = "abc";
    (new Function("return alert(n);"))();
})();



回答2:


When you use the new Function method (which is similar to eval by the way), your code is executed in the global scope! n only exists inside that anonymous function, it's not global.

You shouldn't be using new Function unless it's 100% necessary.

(function(){
    var n = "abc";
    (function(){return alert(n);})();
})();

P.S. alert returns undefined so return alert() doesn't do anything useful.



来源:https://stackoverflow.com/questions/28592127/javascript-new-function-scope-referenceerror

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!