我试图更好地理解module.exports。据我了解,它可以用作双向通信(您可以向模块发送和接收数据。
但是,这没有按我预期的那样工作:
File1.js:
var Test = require("./Balances")
Test.push(12)
Balances.js:
var arrays = [10, 11];
module.exports = arrays
File2.js:
var Test = require("./Balances")
setInterval(function(){console.log(Test)},2000)
我想要的是能够从File1添加到数组,并读取File2中的输出。
File2可以很好地读取初始数组,但是我推送的值从未在File2中显示。
但是,如果我在File1中添加console.log(Test),则该推入的值确实会出现在其中。但是,在重新运行File1时,我没有看到[12,12],只有[12],这意味着第一次推送从未写入余额数组。
知道为什么吗?
当您从另一个JavaScript模块导入变量时,您会通过值而不是通过引用来获取该变量(您在给定的内存地址处创建了该值的副本,而不仅仅是获得了指向该完全相同的变量的指针)。因此,您只对了中的Test
变量进行了突变File1.js
。以反映你的这些变化console.log
中File2.js
,你将有你的突变变再从出口File1.js
和进口到这一点File2.js
,然后做日志。
这是您的代码分析:
File1.js:
// creates copy of the `Balance.js` `arrays` variable
// stores value in new variable `Test`
var Test = require("./Balances") // => [10, 11]
// pushes 12 to the copy
Test.push(12) // => [10, 11, 12]
File2.js:
// creates copy of the `Balance.js` `arrays` variable
// stores value in new variable `Test`
var Test = require("./Balances") // => [10, 11]
// This interval does nothing. The fact is, the mutated
// `arrays` var from `File1.js` does not effect the
// `arrays` var in any other modules scope.
setInterval(function(){console.log(Test)},2000) // => [10, 11]
所有这些都假设您有一个未在此处看到的附加代码,这些附加代码是从入口点开始执行的。正如Thomas在评论中说的那样,运行单个脚本之间没有持久性。
要完成您在帖子中尝试的操作:
Balances.js:
var arrays = [10, 11]
module.exports = arrays
File1.js:
var test = require('./Balances')
test.push(12)
module.exports = test
File2.js:
var test = require('./File1')
function action() {
console.log(test)
}
module.exports = action
main.js(入口点):
var action = require('./File2')
action() // => [10, 11, 12]
跑 $ node main.js
希望这可以帮助!
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句