考虑这两个程序:
testing1.js:
'use strict';
var two=require('./testing2');
two.show();
two.animal='Dog';
two.show();
testing2.js:
'use strict';
var animal='Cat';
function show()
{
console.log(animal);
}
module.exports.animal=animal;
module.exports.show=show;
当我在 Node.js 中运行它时,它会打印“Cat Cat”。我希望它打印“猫狗”。为什么打印“Cat Cat”,如何让它打印“Cat Dog”?
最佳答案
我认为这里的问题是 two.animal
和 var animal
是两个不同的变量。 show
函数始终记录在 testing2.js
var animal
对于 testing2.js
我会做这样的事情:
'use strict';
module.exports = {
animal: 'Cat',
show: function () {
console.log(this.animal); // note "this.animal"
}
}
然后在testing1.js
中:
'use strict';
var two = require('./testing2.js');
two.show(); // => Cat
two.animal = 'Dog'; // now replaces 'Cat'
two.show(); // => Dog
关于javascript - 为什么我不能在 Node.js 中从另一个文件中设置一个导出变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38728296/