【问题标题】:can a exported variable be changed in the original file?可以在原始文件中更改导出的变量吗?
【发布时间】:2019-07-24 10:55:21
【问题描述】:

first.js

var a='this is first.js'

module.exports=a;

second.js

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

console.log(a);

输出:这是 first.js

如果我在 second.js 中更改“a”的内容,这是否也会反映在 first.js 中?如果没有,如果可能的话怎么做?

first.js

var a='this is first.js'

module.export=a;

second.js

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

console.log(a);

【问题讨论】:

标签: javascript node.js


【解决方案1】:

您需要传递一个对象而不是字符串。

first.js

var a = {

    txt : 'this is first.js'
}

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

在 app.js 中,你可以修改它,它会在任何地方反映出来

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

我希望它有所帮助。

【讨论】:

    【解决方案2】:

    没有。在第二个模块中分配给a 只会改变本地的variable,没有别的。

    怎么做?

    导出一个对象,而不是单个值。然后你可以从任何地方修改它的属性。

    // 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';
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-20
      • 2020-03-30
      • 2013-02-21
      • 1970-01-01
      • 2021-02-28
      • 2011-01-19
      • 1970-01-01
      • 2016-01-13
      相关资源
      最近更新 更多