我试过这个:
// mod.js
var a = 1;
this.b = 2;
exports.c = 3;
// test.js
var mod = require('./mod.js');
console.log(mod.a); // undefined
console.log(mod.b); // 2
console.log(mod.c); // 3, so this === exports?
因此,我设想require()可以像这样实现:
var require = function (file) {
var exports = {};
var run = function (file) {
// include "file" here and run
};
run.apply(exports, [file]);
return exports;
}
是那么回事吗?请帮我理解一下require(),或者在哪里可以找到源码。谢谢!
发布于 2012-02-28 15:08:55
发布于 2014-12-24 16:33:17
Andrey展示了它的源代码,但是如果你想知道如何使用它,这里有一个简单易懂的解释(http://nodejs.org/api/modules.html)。
对我来说,这是两个很好的例子。
//foo.js, multiple methods
var circle = require('./circle.js');
console.log( 'The area of a circle of radius 4 is ' + circle.area(4));
//circle.js
var PI = Math.PI;
exports.area = function (r) {
return PI * r * r;
};
exports.circumference = function (r) {
return 2 * PI * r;
};
//bar.js
var square = require('./square.js');
var mySquare = square(2);
console.log('The area of my square is ' + mySquare.area());
//square.js, single method
module.exports = function(width) {
return {
area: function() {
return width * width;
}
};
}
我最喜欢的模式是
(function (controller) {
controller.init = function (app) {
app.get("/", function (req, res) {
res.render("index", {});
});
};
})(module.exports);
发布于 2019-09-27 10:10:45
我进一步挖掘了nodejs源代码/2/,并制作了一个序列图/1/,希望这能给你一个直观的概述。还有另一篇文章http://fredkschott.com/post/2014/06/require-and-the-module-system/也以一种简单的方式解释了require()机制,先看看这篇文章可以帮助你快速理解这个图。
参考:
https://stackoverflow.com/questions/9475792
复制相似问题