I'm trying to do some js code shared between the browser and the nodejs server. To do that, I just use these practises: 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:
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. 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.
Thanks
It does not work because reference
does not point to module.exports
, it points to the object module.exports
points to:
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:
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
. It has no influence on the value of a
.
i want to understand why it is illegal, even though reference===module.exports is true
It is not illegal , this how JavaScript (and most other languages) work. reference === module.exports
is true, because before the assignment, they both refer to the same object. After the assignment, references
refers to a different object than modules.export
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.