简体   繁体   English

Node.js引用module.exports

[英]Nodejs referencing module.exports

I'm trying to do some js code shared between the browser and the nodejs server. 我正在尝试做一些在浏览器和nodejs服务器之间共享的js代码。 To do that, I just use these practises: http://caolanmcmahon.com/posts/writing_for_node_and_the_browser/ 为此,我只使用以下实践: http : //caolanmcmahon.com/posts/writing_for_node_and_the_browser/

The problem is when I want to export a function, not an object. 问题是当我要导出功能而不是对象时。 In node you could do something like: 在节点中,您可以执行以下操作:

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

so that when require is used you can do: 这样,当使用require时,您可以执行以下操作:

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

The problem is when I try to reference the module.exports object in the module and use that reference to overwrite it with my function. 问题是当我尝试引用模块中的module.exports对象并使用该引用用我的函数覆盖它时。 In the module it would be: 在模块中将是:

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

Why this doesn't work? 为什么这不起作用? I don't want to use the easy solution to insert an if inside the clean code, but i want to understand why it is illegal, even though reference===module.exports is true. 我不想使用简单的解决方案在干净的代码中插入if,但是我想理解为什么它是非法的,即使reference === module.exports为true。

Thanks 谢谢

It does not work because reference does not point to module.exports , it points to the object module.exports points to: 它不起作用,因为reference 指向module.exports ,而是指向对象module.exports指向:

module.exports
              \ 
                -> object
              / 
     reference

When you assign a new value to reference , you just change what reference points to, not what module.exports points to: 当您将新值分配给reference ,您只需更改reference指向的内容,而不是module.exports指向的内容:

module.exports
              \ 
                -> object

reference -> function

Here is simplified example: 这是简化的示例:

var a = 0;
var b = a;

Now, if you set b = 1 , then the value of a will still be 0 , since you just assigned a new value to b . 现在,如果你设置b = 1 ,则值a将仍然是0 ,因为你只是分配一个新的值b It has no influence on the value of a . 这对价值没有影响a

i want to understand why it is illegal, even though reference===module.exports is true 我想了解为什么它是非法的,即使reference === module.exports为true

It is not illegal , this how JavaScript (and most other languages) work. 这不是非法的 ,这就是JavaScript(和大多数其他语言)的工作方式。 reference === module.exports is true, because before the assignment, they both refer to the same object. reference === module.exports为true,因为在分配之前,它们都引用相同的对象。 After the assignment, references refers to a different object than modules.export . 分配后, references引用的对象与modules.export不同。

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

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