简体   繁体   中英

can a exported variable be changed in the original file?

first.js

var a='this is first.js'

module.exports=a;

second.js

var a=require('./first');

console.log(a);

output:this is first.js

if i change the content of 'a' in second.js will that reflect in first.js too? if not and if possible how to do it?

first.js

var a='this is first.js'

module.export=a;

second.js

var a=require('./first');

console.log(a);

No. Assigning to a in the second module only changes the local var iable, nothing else.

how to do it?

Export an object, not a single value. Then you can modify its properties from everywhere.

// first.js
module.exports.a = 'this is first.js';

// second.js
var first = require('./first');
console.log(first.a);
first.a = 'this is something else';

You need to pass an object instead of string.

first.js

var a = {

    txt : 'this is first.js'
}

function too() {
    console.log(a.txt);
}
module.exports = { foo: a, too:too };

in the app.js , you can modify it and it will be reflected eveywhere

var a = require("./first");
a.foo.txt = 'hahaha';
console.log(a.foo.txt);
a.too();

I hope it helps.

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.

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