我正在尝试从 Rhino 书中学习 JavaScript。我试图执行书中有关 eval()
的以下代码。我使用 node.js (v0.10.29) 来执行示例。
var geval = eval; // aliasing eval to geval
var x = 'global'; // two global variables
var y = 'global';
function f () {
var x = 'local'; // define a local variable
eval('x += "changed";'); // direct eval sets the local variable
return x;
}
function g () {
var y = 'local'; // define a local variable
geval('y += "changed";'); // indirect eval sets global variable
return y;
}
console.log(f(), x); // => expected 'localchanged global'
console.log(g(), y); // => expected 'local globalchanged'
但是,当尝试使用 geval()
别名时,我在 g()
函数内收到 ReferenceError
:
undefined:1
y += "changed";
^
ReferenceError: y is not defined
at eval (eval at g (/Users/codematix/Learning/learnjs/expressions.js:148:3), <anonymous>:1:1)
at eval (native)
at g (/Users/codematix/Learning/learnjs/expressions.js:148:3)
at Object.<anonymous> (/Users/codematix/Learning/learnjs/expressions.js:153:3)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
据我了解,当我将 eval()
别名为 geval()
时,传递的字符串中的代码将根据 ES5 在全局范围内进行评估。但是,我遇到了 ReferenceError
并且无法理解原因。
虽然我不认为 eval()
是一个关键功能,但我绝对想了解为什么我会遇到这种行为。
附注当我尝试在 Google Chrome 中执行相同的代码时,它似乎很神奇!奇怪!
最佳答案
问题是您正在从模块运行此代码,其中 var y = global;
实际上在模块范围而不是全局范围中定义y
。
In browsers, the top-level scope is the global scope. That means that in browsers if you're in the global scope var something will define a global variable. In Node this is different. The top-level scope is not the global scope; var something inside a Node module will be local to that module.
http://nodejs.org/api/globals.html#globals_global
因此,让它在 Node 中工作的两种可能方法是:
- 按原样在 Node REPL 中运行它
- 在模块中运行它,但将
var y = global;
替换为y = global;
关于javascript - Node.js 全局 eval,抛出 ReferenceError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28251319/