Node.js --- require 中的全局变量

obj.js

var S

function init(value) {
    S = {
        s: value
    }
}

module.exports = {
        S: S,
        init: init
}

index.js

var obj = require('./obj')

obj.init('Hi')

console.log("index.js: " + obj.S)

结果:

node index.js

index.js: undefined    // 为什么呢,明明已经初始化了

=====================================

参考此文换一种方式:
https://www.yangyang.cloud/blog/2016/06/28/nodejs-circular-dependencies/

obj.js

const Module = module.exports;

var S

function init(value) {
    S = {
        s: value
    }
}

Module.S = S
Module.init = init

index.js

var obj = require('./obj')

obj.init('Hi')

console.log("index.js: " + obj.S)

结果:

node index.js

index.js: undefined    // 为什么呢,明明已经初始化了

=====================================

obj.js

class C {
        constructor() {
                this.S = null
        }

        init(value) {
                this.S = { s: value }
        }
}

var obj = new C()
obj.init('Hello')
console.log(obj.S.s)

module.exports = obj

index.js

var obj = require('./obj')

obj.init('Hi')

console.log("index.js: " + obj.S.s)

结果:

node index.js

obj.js: Hello
index.js: Hi     // 全局变量修改成功

看来全局变量必须明确为引用型才可以被改变

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值