使用 eval() 定义 const 变量

Define const variable using eval()

当我尝试使用 var 定义变量时,一切正常。

但是将它定义为 const 并没有按预期工作并且变量未定义。

window.eval("var v = 5;");
document.body.innerHTML += window.v === undefined;

window.eval("const l = 5;");
document.body.innerHTML += window.l === undefined;

我已经在 Chrome 和 Node.js 上测试过了。我错过了什么吗?

提前致谢!

那是因为const默认开启了严格模式。看看当你明确地为两个例子打开严格模式时会发生什么:

window.eval("'use strict'; var v = 5;");
document.body.innerHTML += window.v === undefined;

window.eval("'use strict'; const l = 5;");
document.body.innerHTML += window.l === undefined;

有关严格模式的更多信息,请参阅:

特别是这部分:

Second, eval of strict mode code does not introduce new variables into the surrounding scope. In normal code eval("var x;") introduces a variable x into the surrounding function or the global scope. This means that, in general, in a function containing a call to eval every name not referring to an argument or local variable must be mapped to a particular definition at runtime (because that eval might have introduced a new variable that would hide the outer variable). In strict mode eval creates variables only for the code being evaluated, so eval can't affect whether a name refers to an outer variable or some local variable [emphasis added]

另请参阅这篇文章:

eval 代码中使用 letconst 不会调用严格模式。 letconstlexicalDeclarations,这将它们的范围限制在封闭的词法范围内。

词法作用域由块创建并通过直接调用 eval(参见 Runtime Semantics: PerformEva step 12)。