我有一个文件A.js
,我有一个模块级变量activeCount
。我使用module.exports导出它。我有一个测试文件testA.js
,我在其中检查activeCount
的值。
但A.js
似乎没有看到我在activeCount
到testA.js
所做的更改。我想这可能是因为当我更改activeCount
时,会导致module.exports.activeCount
和activeCount
指向不同的对象。我是否正确分析了这一点,如果是这样,如何在不创建新对象的情况下更改activeCount
的值?
A.js
var activeCount = 0;
...
function reset() {
activeCount = 0;
}
function A() {
...
}
module.exports = A;
module.exports.activeCount = activeCount;
module.exports.reset = reset;
A.prototype.addFunction(...) {
...
activeCount++;
...
}
testA.js
var A = require('A');
test('test1', function (assert) {
var a = new A();
a.addFunction(...);
console.log(A.activeCount); // prints 0 instead of 1
});
test('test2', function (assert) {
A.reset();
var a = new A();
a.addFunction(...);
console.log(A.activeCount); // also prints 0 instead of 1
});
答案 0 :(得分:11)
在Javascript中,当您指定一个整数(或任何基元 - 例如非对象)时,它将被复制到新变量中。因此,对新变量的更改不会影响原始变量。 Javascript没有整数的真正引用类型。
通常的解决方法是导出一个对象(由指针指定),然后将整数作为属性放在该对象上。然后,每个引用该对象的人都会看到更改对象的属性。
事实证明,您已经将activeCount导出为对象的属性(因为它是module.exports
模块中A.js
的属性。所以,您只需要更改“A” “模块从那里使用它而不是使用它的本地副本。有几种不同的方法可以做到这一点。这是一个:
// A.js
function reset() {
// change the exported variable
module.exports.activeCount = 0;
}
function A() {
...
}
module.exports = A;
module.exports.activeCount = 0;
module.exports.reset = reset;
A.prototype.addFunction(...) {
...
// change the exported variable
module.exports.activeCount++;
...
}
现在,您的testA.js模块将按预期工作。
注意,由于您正在执行module.exports = A;
并且函数是对象,因此您还可以在activeCount
模块内引用A
作为A
的属性,它也会解决问题并给出理想的结果:
// A.js
function reset() {
// change the exported variable
A.activeCount = 0;
}
function A() {
...
}
// add properties to our constructor function so those properties
// are also exported
A.activeCount = 0;
A.reset = reset;
module.exports = A;
A.prototype.addFunction(...) {
...
// change the exported variable
module.exports.activeCount++;
...
}