[英]Node.js - changing the value of an exported integer
我有一個文件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
});
在Javascript中,當您指定一個整數(或任何基元 - 例如非對象)時,它將被復制到新變量中。 因此,對新變量的更改不會影響原始變量。 Javascript沒有整數的真正引用類型。
通常的解決方法是導出一個對象(由指針指定),然后將整數作為屬性放在該對象上。 然后,每個引用該對象的人都會看到更改對象的屬性。
事實證明,您已經將activeCount導出為對象的屬性(因為它是A.js
模塊中module.exports
一個屬性。所以,您只需要更改“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;
和函數是對象,你也可以在A
模塊中引用activeCount
作為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++;
...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.