【问题标题】:exporting a private function in node.js / coffeescript在 node.js/coffeescript 中导出私有函数
【发布时间】:2015-02-11 17:40:42
【问题描述】:

我要导出一个函数,叫它someFunction:

someFunction = (foo)->
   console.log(foo)

module.exports.someFunction = someFunction

但我正在考虑将其封装在另一个函数中

someOtherFunction = ()->
    someFunction = (foo)->
        console.log(foo)

使用modules 导出它的正确方法是什么?

【问题讨论】:

  • 你不能;现在它的作用域是外部函数。
  • @Mathletics 这怎么行?他提到封装一个函数,这是非常可行的。为什么这个问题被否决了?
  • someFunction 至少在调用someOtherFunction 之前无法导出。因此,任何可能正确的方法都将依赖于如何以及何时完成。
  • 您能解释一下您为此想到的上下文或用例吗?

标签: javascript node.js coffeescript


【解决方案1】:

你的意思是这样的:

module.exports = function() {
  return function(a) {
     //encapsulated
     console.log(a);
  };
};

这可以通过以下方式调用:

var test = require('./test'); // file with function

var func = test();
func(a); // console.log(a);

这就是你想要实现的方式吗?

【讨论】:

  • 谢谢,但不,我希望封装导出上下文以外的其他地方。
  • @fox 我不明白你的问题。
  • @fox 我也不明白。您需要导出 something 才能访问某些内容。 exports 直接或通过函数。
  • 抱歉,我的回答可能含糊不清。我要做的是导出一组可以封装在外部函数中的内部函数,如上面的示例所示。我想在我的代码中保留someFunctionsomeOtherFunction 之间的层次结构,但只导出someFunction
  • @fox someOtherFunction 可能是used as a closure,也可能是IIFEsomeFunctionrevealed from it。不过,对于Node.js' module scope,这样的闭包已经存在于整个.js 文件周围,module.exports 用于显示。
猜你喜欢
  • 1970-01-01
  • 2014-04-30
  • 2013-07-28
  • 1970-01-01
  • 2016-08-26
  • 1970-01-01
  • 2021-08-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多