Javascript 无法理解此Express JS源代码片段
我试图理解Express JS源代码,这是导出Express的主要模块Javascript 无法理解此Express JS源代码片段,javascript,node.js,express,Javascript,Node.js,Express,我试图理解Express JS源代码,这是导出Express的主要模块 module.exports = createApplication; function createApplication() { var app = function(req, res, next) { app.handle(req, res, next); }; mixin(app, EventEmitter.prototype, false); mixin(app, proto, fal
module.exports = createApplication;
function createApplication() {
var app = function(req, res, next) {
app.handle(req, res, next);
};
mixin(app, EventEmitter.prototype, false);
mixin(app, proto, false);
// expose the prototype that will get set on requests
app.request = Object.create(req, {
app: { configurable: true, enumerable: true, writable: true, value: app }
})
// expose the prototype that will get set on responses
app.response = Object.create(res, {
app: { configurable: true, enumerable: true, writable: true, value: app }
})
app.init();
return app;
}
我对这段代码感到困惑
var app = function(req, res, next) {
app.handle(req, res, next);
};
变量
app
同时在函数内部分配和使用。这怎么行?其他任何地方都没有应用程序的定义。找到真正的源。函数被创建并分配给app
变量。这是一个普通的函数表达式赋值
然后,两行mixin()
向app
函数添加方法。因此,在调用这些函数之后,它有类似于app.handle()
和app.init()
的功能
然后,添加另外两个属性app.request
和app.response
然后,调用app.init()
然后,稍后会调用app
函数(当http请求到达时),当调用该函数时,它会调用app.handle()
,该函数只是调用本身的属性函数。这是合法的。这类似于在更传统的对象中调用this.handle()
下面是一个让你最困惑的部分的演示:
var测试=函数(){
试验。剂量测定();
}
test.doSomething=函数(){
控制台日志(“doSomething”);
}
test();//导致调用test.doSomething()
Oh yes。现在有道理了。谢谢