分配“出口"到nodejs模块中的功能不起作用 [英] assigning "exports" to a function in nodejs module doesn't work

查看:22
本文介绍了分配“出口"到nodejs模块中的功能不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个文件(otherFile.js)中,我有这个文件:

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

,如果在otherFile.js中,则改为:

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();

然后完美运行.为什么不允许我将函数分配给exports变量?

then it works perfectly. Why is it that I'm not allowed to assign a function to the exports variable?

推荐答案

如果要更改导出的对象本身,则将其分配给 module.exports .这应该可以工作(在otherFile.js中):

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() {}

详细说明原因:

重新分配变量不会更改之前引用的对象(基本上就是您正在做的事情).一个简单的例子是这样:

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);

基本上,通过将导出分配给函数,您希望变量 x 的值为 {test:'xyz'} ,但它仍为 {test:'abc'} ,因为该函数引入了一个新变量(但是该变量仍引用同一对象,因此更改 a.test 会同时更改两者的输出).基本上,这也是CommonJS模块(Node所使用的)的工作方式.

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.

这篇关于分配“出口"到nodejs模块中的功能不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆