Node.js:以文件或交互方式运行脚本会产生不同的结果

如果我保存下面的行并像./node saved.js一样运行

var that = this; that.val1 = 109; var f1 = function(){return this;} var f2 = function(){return this;} var that1 = f1(); var that2 = f2(); console.log(that1.val1)//undefined that1.val2=111; console.log(that2.val2)//111 

我得到这个结果

 undefined 111 

但是,如果我把它粘贴到已经启动的shell ./node,我就可以得到

 ... ... > console.log(that1.val1)//undefined 109 undefined > that1.val2=111; 111 > console.log(that2.val2)//111 111 

为什么第一个console.log的输出不同?

当你在脚本中运行它时,函数内部的this内部引用了一个不同于它在你的函数外部的对象。 例如,我在脚本的开头做了这个改变:

 var that = this; console.log(this) that.val1 = 109; var f1 = function(){console.log(this); console.log("eq: " + (this === that));return this;} 

当第二行以node test.js运行时,我得到一个空对象,然后f1里面的一个执行了更深的几行,这是一个非常不同的对象。

当它从Node REPL运行时,我在两个地方都得到了一个与node test.js f1内部的对象相匹配的对象。 因此,在这两种情况下, that.va1 = 109对不同的对象起作用,这就是为什么你看到不同。

编辑:请参阅Jonathan Lonowski关于两个不同对象的问题的评论。