问题
in one file (otherFile.js) I have this:
exports = function() {}
in my main file I have this:
var thing = require('./otherFile.js');
new thing();
however this gives me the following error:
TypeError: object is not a function
and if in otherFile.js I have this instead:
exports.myFunction = function() {}
and in my main file I have this:
var thing = require('./otherFile.js');
new thing.myFunction();
then it works perfectly. Why is it that I'm not allowed to assign a function to the exports variable?
回答1:
If you want to change the exported object itself you will have assign it to module.exports. This should work (in otherFile.js):
module.exports = function() {}
To elaborate a little more why:
Reassigning a variable does not change the object it referenced before (which is basically what you are doing). A simple example would be this:
function test(a) {
a = { test: 'xyz' };
console.log(a);
}
var x = { test: 'abc' };
test(x);
console.log(x);
Basically by assigning exports to the function you'd expect the variable x to have a value of { test: 'xyz' } but it will still be { test: 'abc' } because the function introduces a new variable (which is still referencing the same object however so changing a.test will change the output of both). That's basically how CommonJS modules (which is what Node uses) work, too.
回答2:
Consider this code:
!function(exports) {
// your module code
exports = 12345
}(module.exports)
console.log(module.exports)
It won't work, and it's easy to see why. Node.js exports object is defined exactly like this, with an exception of arguments ordering.
So always use module.exports instead of exports, it'll do the right thing.
来源:https://stackoverflow.com/questions/22364521/assigning-exports-to-a-function-in-nodejs-module-doesnt-work