I want to do something like this in Dispatc开发者_如何学Pythonh.js
function handle(msg) {
....
}
exports = handle;
and this in the calling index.js
var dispatch = require("./Dispatch);
dispatch("data");
Any ideas?
exports = handle
This creates a local variable called exports
. This is different from overwriting module.exports
.
module.exports = handle
This overwrites the exports variable that lives in module scope, this will then be read by require
.
In the browser window["foo"]
and foo
are the same, however in node module["foo"]
and foo
behave subtly different.
The local variable scope context and module
are not the same thing.
Do:
function handle(msg) {
....
}
module.exports = handle;
and it works the way you want.
The problem behind this issue (exports
vs module.exports
vs exports.something
) is best described in this article:
http://www.alistapart.com/articles/getoutbindingsituations
The first version (exports = handle
) is exactly the problem: the missing binding that is mandatory in javascript:
exports = handle
means window.exports = handle
(or whatever node.js has as the global object)
Another way of seeing the problem is thinking about how node could load your module:
function loadModule(module, exports) {
inside here comes your module code
}
If your code overwrites the exports
parameter (exports = handle
), this change is not visible from the outside of this function. And for this overwriting one can use the module
object.
The problem would not occur if exports would be a variable visible in the scope where the function body is.
精彩评论