2014-01-20 26 views
1

,如果我救下面的線路和運行像./node saved.js的Node.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的輸出不同?

+0

REPL(交互模式)在全局範圍內執行代碼,其中模塊文件[this === global]在[它們自己的範圍內運行](http://nodejs.org/api/globals.html#globals_global_objects )where this == module.exports'。 –

回答

1

當您在腳本中運行它時,函數內部的this引用與它在函數外部不同的對象。例如,我做了這個變化到你的腳本的開頭:

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

當那第二行執行,而隨後執行的f1內的一個幾行更深層次的運行它作爲node test.js,我得到一個空的對象, ,這是一個非常不同的對象。

當這是一個從節點REPL運行,我得到一個對象匹配從內部f1node test.js版本在這兩個地方的人。因此,that.va1 = 109在兩種情況下對不同的對象起作用,這也是您看到區別的原因。

編輯:請參閱Jonathan Lonowski關於兩個不同對象的問題的評論。

相關問題