To expand Raynos answer ...
exports is basically an alias for module.exports - I recommend just not using it. You can set methods and properties from a module by setting them to module.exports , as shown below:
//file 'module1.js' module.exports.foo = function () { return 'bar' } module.exports.baz = 5
Then you will access it in your code:
var module1 = require('module1') console.log(module1.foo()) console.log(module1.baz)
You can also override module.exports to just provide one object on demand:
//glorp.js module.exports = function () { this.foo = function () { return 'bar' } this.baz = 5 return this // need to return `this` object here }
You now have a good prototype:
var g1 = new require('glorp')() console.log(g1.foo()) console.log(g1.baz)
There are many other ways to play with module.exports and require . Just remember that require('foo') always returns the same instance , even if you call it several times.
Note
To perform the following steps
var g1 = new require('glorp')() console.log(g1.foo()) console.log(g1.baz)
this should be returned in the function assigned by module.exports . Otherwise, you get a TypeError :
console.log(g1.foo()) ^ TypeError: Cannot read property 'foo' of undefined
Tamzin Blake May 26 '11 at 1:04 AM 2011-05-26 01:04
source share