我试过这个:
// 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?
Run Code Online (Sandbox Code Playgroud)
所以我想象require()可能是这样实现的:
var require = function (file) {
var exports = {};
var run = function (file) {
// include "file" here and run
};
run.apply(exports, [file]);
return exports;
}
Run Code Online (Sandbox Code Playgroud)
是对的吗?请帮我理解require(),或者在哪里可以找到源代码.谢谢!