Node Modules - Export variables and export functions that reference it?

The easiest way to explain with code is:

##### module.js var count, incCount, setCount, showCount; count = 0; showCount = function() { return console.log(count); }; incCount = function() { return count++; }; setCount = function(c) { return count = c; }; exports.showCount = showCount; exports.incCount = incCount; exports.setCount = setCount; exports.count = count; // let also export the count variable itself #### test.js var m; m = require("./module.js"); m.setCount(10); m.showCount(); // outputs 10 m.incCount(); m.showCount(); // outputs 11 console.log(m.count); // outputs 0 

Exported functions work as expected. But I do not understand why m.count is not also 11.

+6
source share
3 answers

exports.count = count

Set the count property of the exports object to count . That is 0.

Everything is passed by value, not by reference.

If you defined count as getter, for example:

 Object.defineProperty(exports, "count", { get: function() { return count; } }); 

Then exports.count will always return the current count value and thus will be 11

+13
source

Correct me if I am wrong, but numbers are immutable types. When you change the count value, your link also changes. Therefore, exports.count refers to the old count value.

0
source

In JavaScript, functions and objects (including arrays) are assigned to variables by reference, and strings and numbers are assigned by value, that is, by creating a copy. If var a = 1 and var b = a and b++ , a will still be 1.

In this line:

 exports.count = count; // let also export the count variable itself 

You made a copy of the value of the count variable. The operations setCount (), incCount (), and showCount () operate on the count variable inside the closure, so m.count will not be affected again. If these variables worked on this.count, then you will get the expected behavior, but you probably don't want to export the count variable anyway.

0
source

Source: https://habr.com/ru/post/897117/


All Articles