Node.js的模块/输出系统:是否有可能一个模块导出为一个功能

Node.js的模块/输出系统:是否有可能一个模块导出为一个功能

问题描述:

我想要做这样的事情在Dispatch.jsNode.js的模块/输出系统:是否有可能一个模块导出为一个功能

function handle(msg) { 
    .... 
} 
exports = handle; 

,这在调用index.js

var dispatch = require("./Dispatch); 
dispatch("data"); 

有什么想法?

exports = handle

这将创建一个名为exports一个局部变量。这与覆盖module.exports不同。

module.exports = handle

这将覆盖出口变量,居住在模块范围内,这就要通过require读取。

在浏览器window["foo"]foo是相同的,但在节点module["foo"]foo行为微妙不同。

本地变量作用域上下文和module不是同一回事。

做:

function handle(msg) { 
    .... 
} 
module.exports = handle; 

和它的作品,你想要的方式。

+1

或module.exports = function(msg){} – Tom 2011-05-09 16:18:10

exports VS module.exports VS exports.something)这背后的问题的问题在这篇文章中是最好的描述:

http://www.alistapart.com/articles/getoutbindingsituations

第一个版本(exports = handle)是完全的问题:缺少的绑定是强制性的的javascript:

exports = handle意味着window.exports = handle(或任何的node.js具有与全局对象)

看到问题的另一个办法就是想着节点可以如何加载模块:

function loadModule(module, exports) {

里面来了你的模块代码

}

如果你的代码覆盖exports参数( exports = handle),这个改变从这个函数的外部是不可见的。而对于这种覆盖,可以使用module对象。

如果导出将是函数体所在作用域中可见的变量,则不会发生此问题。