为什么节点的全局此对象为空?

时间:2014-10-16 16:44:35

标签: node.js

看看这种奇怪的行为:

/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执行?

1 个答案:

答案 0 :(得分:4)

this设置为exports / module.exports(尽管应使用后两者)。

所以你的代码目前相当于:

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

由于您未向exports附加任何内容,因此找不到您的FooBar()功能。

相关问题