节点模块-导出变量与导出引用变量的函数? [英] Node Modules - exporting a variable versus exporting functions that reference it?

查看:54
本文介绍了节点模块-导出变量与导出引用变量的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最容易用代码解释:

##### 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.

The exported functions work as expected. But I'm not clear why m.count isn't also 11.

推荐答案

exports.count = count

您将对象exports上的属性count设置为count的值. IE. 0.

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.

如果要将count定义为像这样的吸气剂:

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

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

然后exports.count总是返回count的当前值,因此为11

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

这篇关于节点模块-导出变量与导出引用变量的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆