0

Look at this weird behaviour:

/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

Why is node forgetting the contents of its global this object when executing code from a file, as opposed to from STDIN?

daxim
  • 39,270
  • 4
  • 65
  • 132

1 Answers1

4

this is set to exports/module.exports (although the latter two should be used instead).

So your code is currently equivalent to:

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

and since you haven't attached anything to exports, your FooBar() function is not found.

mscdex
  • 104,356
  • 15
  • 192
  • 153