Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I change variable in a function from another file?

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?

like image 751
Alan Huang Avatar asked Jan 04 '23 20:01

Alan Huang


1 Answers

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.

Global

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;

Pass and Return

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;
};

Put value in object and pass reference to object

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;
};
like image 144
jfriend00 Avatar answered Jan 06 '23 12:01

jfriend00