将代码放入文件(test.js),然后执行node test.js
。你会得到:
ReferenceError: val is not defined
直接在node环境(或浏览器控制台)复制代码,不会报错。
let val = "global"
function foo2() {
let val = "local"
let f = eval
return f("val")
}
foo2()
最佳答案
如果您通读 MDN page on eval
你会看到:
if you use the eval function indirectly, by invoking it via a reference other than eval, as of ECMAScript 5 it works in the global scope rather than the local scope.
当您在 Node 中运行此代码时,它将在全局对象中查找 val
并且不会找到它,因为即使在外部作用域中声明的变量对于 Node 中的封闭模块也是私有(private)的 -除非您将它们放在那里,否则它们不会出现在全局命名空间中。这会导致您注意到的错误。
然而,这将在 Node 中记录 global
:
global['val'] = "global"
function foo2() {
let val = "local"
let f = eval
return f("val")
}
console.log(foo2())
关于javascript - 间接调用 eval,但出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53929606/