为什么我不能在Node.js中的另一个文件中设置一个导出的variables?
考虑这两个程序:
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”。 我期望它打印“猫狗”。 为什么要打印“猫猫”,怎样才能打印出“猫狗”?
我认为这里的问题是two.animal
和var animal
是两个不同的variables。 show
函数总是logging在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总是通过值传递variables,而不是通过引用 – 当然,除非它是一个对象或函数,其中“值”是一个引用。 当我将动物variables复制到module.exports.animal时,它实际上并不复制该variables,它复制单词“猫”。 更改导出的variables不会影响原始动物variables。 我没有在tests2.js中导出variables,而是创build了一个setter。 出口的二传手,并使用它,而不是试图设置动物直接使其行为我想要的方式。
testing1.js:
'use strict'; var two=require('./testing2'); two.show(); two.setAnimal('Dog'); two.show();
testing2.js:
'use strict'; var animal='Cat'; function show() { console.log(animal); } function setAnimal(newAnimal) { animal=newAnimal; } module.exports.setAnimal=setAnimal; module.exports.show=show;