Node.js全局评估,引发ReferenceError

我正在尝试从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() ,传递的string中的代码将按照ES5在全局范围内进行评估。 但是,我遇到了ReferenceError ,无法理解为什么。

虽然我不认为eval()是一个关键特性,但是我当然想明白为什么我会遇到这种行为。

PS当我试图在谷歌浏览器中执行相同的代码,它似乎像一个魅力工作! 奇怪!

问题是你正在从一个模块运行这个代码,其中var y = global; 实际上在模块范围内定义了y ,而不是全局范围。

在浏览器中,顶级范围是全局范围。 这意味着在浏览器中,如果你在全局范围内,var将会定义一个全局variables。 在Node中,这是不同的。 顶级范围不是全球范围; 在Node模块内的var内容将是该模块的本地内容。

http://nodejs.org/api/globals.html#globals_global

因此,有两种可能的方法可以让Node在Node中工作:

  1. 像在节点REPL中一样运行它
  2. 在模块中运行它,但replacevar y = global; 只有y = global;