最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Node Modules - exporting a variable versus exporting functions that reference it? - Stack Overflow

programmeradmin0浏览0评论

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.

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.

Share Improve this question asked Sep 11, 2011 at 22:45 David EGPDavid EGP 7,0992 gold badges19 silver badges7 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 14

exports.count = count

Your setting a property count on an object exports to be the value of count. I.e. 0.

Everything is pass by value not pass by reference.

If you were to define count as a getter like such :

Object.defineProperty(exports, "count", {
  get: function() { return count; }
});

Then exports.count would always return the current value of count and thus be 11

Correct me if I am wrong, but numbers are immutable types. When you change the value of count then your reference changes too. So exports.count references to the old count value.

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 and var b = a and b++, a will still equal 1.

On this line:

exports.count = count; // let's also export the count variable itself

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.

发布评论

评论列表(0)

  1. 暂无评论