JavaScript新功能范围ReferenceError [英] JavaScript new Function scope ReferenceError

查看:52
本文介绍了JavaScript新功能范围ReferenceError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么办法可以使下面的代码正常工作?

is there any way to make the code below working?

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

如果我在浏览器中运行代码,结果是:"未捕获的ReferenceError:未定义".

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

此外,我还需要使其他变量(例如"n")也可以在新功能"中访问.

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

请帮助,谢谢

推荐答案

因此,您需要将该变量设置为全局变量.

So you need to make that variables global.

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

这篇关于JavaScript新功能范围ReferenceError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆