考虑这两个方案:
测试1.js:
'use strict';
var two=require('./testing2');
two.show();
two.animal='Dog';
two.show();测试2.js:
'use strict';
var animal='Cat';
function show()
{
console.log(animal);
}
module.exports.animal=animal;
module.exports.show=show;当我在Node.js中运行这个程序时,它会打印“猫猫”。我以为它会印上“猫狗”。为什么它要打印“猫猫”,我如何让它打印“猫狗”?
发布于 2016-08-02 19:06:04
我认为问题在于,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发布于 2016-08-02 19:36:04
我想我想出了我自己问题的答案。Javascript总是通过值传递变量,而不是引用-当然,除非它是一个对象或函数,其中的“值”是一个引用。当我将动物变量复制到module.exports.animal时,它实际上不是复制这个变量,而是复制单词"Cat“。更改导出变量不会影响原始动物变量。我没有在testing2.js中导出变量,而是创建了一个setter。导出设置器,并使用它而不是试图直接设置动物,使它的行为方式,我想。
测试1.js:
'use strict';
var two=require('./testing2');
two.show();
two.setAnimal('Dog');
two.show();测试2.js:
'use strict';
var animal='Cat';
function show()
{
console.log(animal);
}
function setAnimal(newAnimal)
{
animal=newAnimal;
}
module.exports.setAnimal=setAnimal;
module.exports.show=show;https://stackoverflow.com/questions/38728296
复制相似问题