assigning “exports” to a function in nodejs module doesn't work

て烟熏妆下的殇ゞ 提交于 2020-04-21 16:30:54

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!