V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
zxCoder
V2EX  ›  问与答

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

  •  
  •   zxCoder · 2020-12-06 10:22:22 +08:00 · 1401 次点击
    这是一个创建于 1245 天前的主题,其中的信息可能已经有所发展或是发生改变。

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

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

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

    因为 JS 里通常都是值传递,除了个别情况比如 object(包括数组) 或者 arguments,你赋值给 module.exports 的对象里的 str 属性是一个值不是一个引用。
    SergeGao
        6
    SergeGao  
       2020-12-06 22:54:21 +08:00
    楼上+1, 用 es module 或者用 get
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1544 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 16:41 · PVG 00:41 · LAX 09:41 · JFK 12:41
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.