I have some code like this:
//app.js
var r=require("./second.js");
var a=1;
r.second(a);
console.log(a);
And my second.js looks like this:
//second.js
module.exports.change=function(a){
a=2;
}
Currently console.log(a) only show 1, I did a bit of research saying I can't pass it as a variable because variable is passed as value. I thought about using global.a. However, it doesn't work too because a is stored as a module variable, not a global variable, and I don't want to set it as a global variable.
How do I solve it?
The main answer is that you can't do it exactly as you asked. A variable defined as you have a
in app.js is private to the scope of a
and only other code within app.js can modify it.
There are a number of other ways you can structure things such that module B can modify something in module A or cause something to be modified in module A.
You can make a
global. This is not recommended for a variety of reasons. But you could make it a property of the global object by changing your declaration of a
to:
global.a = 1;
Then, in module B, you can directly set:
global.a = 2;
You can pass a
into a function in module B and have that function return a new value that you assign back into a
.
const b = require('moduleB');
let a = 1;
a = b.someFunction(a);
console.log(a); // 2
Then, inside of moduleB, you can modify propertys on a
directly:
// inside of moduleB
module.exports.someFunction = function(a) {
return ++a;
};
Rather than storing the value in a simple variable, you can store it as a property of an object an you can then pass a reference to that object. Objects in Javascript are passed by ptr so some other function you pass the object to can modify its properties directly.
const b = require('moduleB');
let a = {someProperty: 1};
b.someFunction(a);
console.log(a.someProperty); // 2
Then, inside of moduleB, you can modify propertys on a
directly:
// inside of moduleB
module.exports.someFunction = function(obj) {
obj.someProperty = 2;
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With