V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
zxCoder
V2EX  ›  问与答

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

  •  
  •   zxCoder · Dec 6, 2020 · 1789 views
    This topic created in 1968 days ago, the information mentioned may be changed or developed.

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

    因为 JS 里通常都是值传递,除了个别情况比如 object(包括数组) 或者 arguments,你赋值给 module.exports 的对象里的 str 属性是一个值不是一个引用。
    SergeGao
        6
    SergeGao  
       Dec 6, 2020
    楼上+1, 用 es module 或者用 get
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3564 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 40ms · UTC 11:54 · PVG 19:54 · LAX 04:54 · JFK 07:54
    ♥ Do have faith in what you're doing.