2014-10-16 51 views
0

看看這個怪異的行爲:爲什麼節點的全局這個對象是空的?

/tmp$ node -v 
v0.10.31 
/tmp$ cat foo.js 
function FooBar() { 
    this.some_method = function() { 
     return 42 
    } 
} 
var class_name = "FooBar" 
console.log((new this[class_name]).some_method()) 
/tmp$ node < foo.js 
42 
/tmp$ node foo.js 

/tmp/foo.js:7 
console.log((new this[class_name]).some_method()) 
      ^
TypeError: undefined is not a function 
    at Object.<anonymous> (/tmp/foo.js:7:14) 
    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) 
    at node.js:906:3 

爲什麼從一個文件中執行代碼時,節點忘記其全球this對象的內容,從STDIN反對?

回答

4

this設置爲exports/module.exports(儘管應該使用後兩者)。

所以,你的代碼是目前相當於:

console.log((new exports[class_name]).some_method()) 

因爲你不附加任何東西exports,你FooBar()功能是找不到的。

相關問題