节点模块 - 导出变量与导出引用它的函数?
最容易用代码解释:
##### module.js
var count, incCount, setCount, showCount;
count = 0;
showCount = function() {
return console.log(count);
};
incCount = function() {
return count++;
};
setCount = function(c) {
return count = c;
};
exports.showCount = showCount;
exports.incCount = incCount;
exports.setCount = setCount;
exports.count = count; // let's also export the count variable itself
#### test.js
var m;
m = require("./module.js");
m.setCount(10);
m.showCount(); // outputs 10
m.incCount();
m.showCount(); // outputs 11
console.log(m.count); // outputs 0
导出的函数按预期工作。但我不清楚为什么 m.count 不是 11。
Easiest to explain with code:
##### module.js
var count, incCount, setCount, showCount;
count = 0;
showCount = function() {
return console.log(count);
};
incCount = function() {
return count++;
};
setCount = function(c) {
return count = c;
};
exports.showCount = showCount;
exports.incCount = incCount;
exports.setCount = setCount;
exports.count = count; // let's also export the count variable itself
#### test.js
var m;
m = require("./module.js");
m.setCount(10);
m.showCount(); // outputs 10
m.incCount();
m.showCount(); // outputs 11
console.log(m.count); // outputs 0
The exported functions work as expected. But I'm not clear why m.count isn't also 11.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
exports.count = count
将对象
exports
上的属性count
设置为count
的值。即0。一切都是按值传递而不是按引用传递。
如果您将
count
定义为这样的 getter:那么
exports.count
将始终返回count
的当前值,因此为 11exports.count = count
Your setting a property
count
on an objectexports
to be the value ofcount
. I.e. 0.Everything is pass by value not pass by reference.
If you were to define
count
as a getter like such :Then
exports.count
would always return the current value ofcount
and thus be 11如果我错了请纠正我,但数字是不可变的类型。当您更改
count
的值时,您的引用也会发生变化。因此,exports.count
引用了旧的count
值。Correct me if I am wrong, but numbers are immutable types. When you change the value of
count
then your reference changes too. Soexports.count
references to the oldcount
value.在 JavaScript 中,函数和对象(包括数组)通过引用分配给变量,字符串和数字通过值(即通过复制)分配。如果
var a = 1
和var b = a
和b++
,a
仍等于 1。在这一行:
您创建了 count 变量的按值副本。 setCount()、incCount() 和 showCount() 操作都对闭包内的 count 变量进行操作,因此 m.count 不会再次被触及。如果这些变量在 this.count 上运行,那么您将得到您期望的行为 - 但您可能无论如何都不想导出 count 变量。
In JavaScript, functions and objects (including arrays) are assigned to variables by reference, and strings and numbers are assigned by value--that is, by making a copy. If
var a = 1
andvar b = a
andb++
,a
will still equal 1.On this line:
you made a by-value copy of the count variable. The setCount(), incCount() and showCount() operations all operate on the count variable inside the closure, so m.count doesn't get touched again. If those variables were operating on this.count, then you'd get the behavior you expect--but you probably don't want to export the count variable anyway.