繁体   English   中英

Node.js引用module.exports

[英]Nodejs referencing module.exports

我正在尝试做一些在浏览器和nodejs服务器之间共享的js代码。 为此,我只使用以下实践: http : //caolanmcmahon.com/posts/writing_for_node_and_the_browser/

问题是当我要导出功能而不是对象时。 在节点中,您可以执行以下操作:

var Constructor = function(){/*code*/};
module.exports = Constructor;

这样,当使用require时,您可以执行以下操作:

var Constructor = require('module.js');
var oInstance = new Constructor();

问题是当我尝试引用模块中的module.exports对象并使用该引用用我的函数覆盖它时。 在模块中将是:

var Constructor = function(){/*code*/};
var reference = module.exports;
reference = Constructor;

为什么这不起作用? 我不想使用简单的解决方案在干净的代码中插入if,但是我想理解为什么它是非法的,即使reference === module.exports为true。

谢谢

它不起作用,因为reference 指向module.exports ,而是指向对象module.exports指向:

module.exports
              \ 
                -> object
              / 
     reference

当您将新值分配给reference ,您只需更改reference指向的内容,而不是module.exports指向的内容:

module.exports
              \ 
                -> object

reference -> function

这是简化的示例:

var a = 0;
var b = a;

现在,如果你设置b = 1 ,则值a将仍然是0 ,因为你只是分配一个新的值b 这对价值没有影响a

我想了解为什么它是非法的,即使reference === module.exports为true

这不是非法的 ,这就是JavaScript(和大多数其他语言)的工作方式。 reference === module.exports为true,因为在分配之前,它们都引用相同的对象。 分配后, references引用的对象与modules.export不同。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM