nodejs module.export 的变量可以修改吗

2020-12-06 10:22:22 +08:00
 zxCoder

a.js

let str="hello";
let update=(s)=>{
    str=s;
}
module.exports={
    str,
    update,
}

b.js

const{str,update}=require("./a");

console.log(str);
update("world");
console.log(str);

有什么方法可以动态修改吗

1421 次点击
所在节点    问与答
6 条回复
wukongkong
2020-12-06 10:29:18 +08:00
现在不能吗?好像 important 形式是可以的,一个是传递值,一个是传递引用
mxT52CRuqR6o5
2020-12-06 11:29:58 +08:00
module.exports = {
get str(){ return str},
update,
}
mxT52CRuqR6o5
2020-12-06 11:31:19 +08:00
@mxT52CRuqR6o5
然后用的时候实时取值
把 require('./a')的引用存下来,或者每次都 require('./a')
yazoox
2020-12-06 13:11:51 +08:00
添加一个方法,getstr(),返回 str 的值。然后,export getstr 方法就可以了。
morethansean
2020-12-06 18:12:06 +08:00
用 ES module 或者
exports.str = 123;
exports.update = s => exports.str = s;

因为 JS 里通常都是值传递,除了个别情况比如 object(包括数组) 或者 arguments,你赋值给 module.exports 的对象里的 str 属性是一个值不是一个引用。
SergeGao
2020-12-06 22:54:21 +08:00
楼上+1, 用 es module 或者用 get

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/732579

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX