我将一个变量值从 file1.js 导出到 file2.js,它可以正常工作,但是如果我想从 file1.js 中的 file2.js 更改该变量的值,它就不起作用。这是否适用于只读,如果可以,我如何连接这两个文件,我可以将值从一个文件更改为另一个文件,反之亦然?
更新:如果在 file1.js 我有let count = 0
,并且从 file2.js 我想将计数值更改为count = 2
,我该如何更改它,因为它不会更改为 file1..
更新 2 - 已解决:
文件1.js
let var1 = 55 ;
function testFunk(reVar, i){
console.log(var1, 'file1')
if( reVar == 'read' ){
return var1
} else if( reVar == 'change' ){
console.log(' change ')
var1 = var1 + i ;
return var1
}
}
module.exports = { testFunk , var1 }
文件2.js
var file1 = require("./file1.js") ;
let var1 ;
testFunk1( )
function testFunk1( ){
setTimeout(() => {
var1 = file1.testFunk( 'read') ;
testFunk1( )
}, 20);
}
setInterval(() => {
file1.testFunk('change', 1 ) ;
console.log( var1 , 'file1' ) ;
}, 1000);
这样我可以从 file1 中读取变量值,更改它们,然后再次读取更改后的值。这是我问的,希望你现在明白了。如果您有任何其他更好的解决方案,请显示它..