模块导出场景混乱

时间:2014-07-17 01:35:12

标签: javascript node.js module

我不理解module.exports nodejs概念的某些情景。

math.js

var add = function(a, b){
    return a + b;
}

multiply = function(a, b){
    return a * b;
}

情景1:

app.js

require("./math")

//can I use add?
//can I use multiply?

情景2:

app.js

var math = require("./math")

//can I use math.add?
//can I use math.multiply?

我在每个场景中都提出了我的问题。 谢谢你的帮助。

1 个答案:

答案 0 :(得分:1)

  

将功能和对象添加到您的根目录   模块,您可以将它们添加到特殊的导出对象。

     

模块本地的变量将是私有的,就像模块一样   被包裹在一个功能中。在此示例中,变量PI是私有的   to circle.js。

你的两个场景都不会起作用(正如你刚刚尝试过的那样你会注意到的)。 您要使用的所有内容都需要分配给(module-)本地exports对象上的module属性。

请参阅nodejs.org/api/modules.html

上的示例

编辑: 想象一下需要做以下的事情

(function (module, exports) {
  var im_local = 123;
  im_global = 321;
  // Your module code here
})(module, module.exports);
return module.exports;

请注意,im_global实际上是新的javascript标准无效,但在严格模式下不会因为 向后兼容/怪异模式V8 javascript引擎的行为。