无法在Node.js ES6中使用eval创建变量 [英] Fail to create variable using eval in Node.js ES6

查看:409
本文介绍了无法在Node.js ES6中使用eval创建变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎无法在Node.js ES6中使用eval创建变量,但我不明白为什么.这在CentOS 7上发生在我身上,但我不认为OS是这里的问题.

It seems not possible to create a variable using eval in Node.js ES6 but I can't understand why. This happens to me on CentOS 7, but I don't believe OS is the problem here.

常规Node.js文件(test.js):

Regular Node.js file (test.js):

eval("var a=1");
console.log(a);

使扩展名为.mjs的文件与Node.js ES6(test.mjs)一起运行:

Make the same file with .mjs extension to run with Node.js ES6 (test.mjs):

eval("var a=1");
console.log(a);

然后,使用Node.js和Node.js ES6运行2个文件:

After that, run the 2 files with Node.js, and Node.js ES6:

$ node test.js
1

$ node --experimental-modules test.mjs
(node:9966) ExperimentalWarning: The ESM module loader is experimental.
ReferenceError: a is not defined
    at file:///temp/test.mjs:2:13
    at ModuleJob.run (internal/modules/esm/module_job.js:96:12)

这是与ES6有关的问题吗?我在浏览器的控制台上尝试过,问题是相同的:

Is it an issue related to ES6? I tried on browser's console and the problem is the same:

>> eval("var a=1"); console.log(a);
   1

>> class c { static f(){ eval("var a=1"); console.log(a); } }
   c.f()
   ReferenceError: a is not defined

我正在使用Node.js 10.9.0,这是一个错误还是背后的原因?

I'm using Node.js 10.9.0, is it a bug or there's a reason behind it?

推荐答案

在严格模式下,在eval()语句内部创建的变量仅可用于该代码.它不会在您的本地范围内创建新变量(这是

In strict mode, variables created inside an eval() statement are available only to that code. It does not create new variables in your local scope (here's a good article on the topic) whereas it can create variables in the local scope when not in strict mode.

并且,默认情况下,mjs模块以严格模式运行.默认情况下,常规的node.js脚本文件未处于严格模式.因此,严格模式设置上的差异会导致eval()的行为发生差异.

And, mjs modules run in strict mode by default. A regular node.js script file is not in strict mode by default. So, the difference in strict mode setting causes a difference in behavior of eval().

这篇关于无法在Node.js ES6中使用eval创建变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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