不能理解这个Express JS源代码片段

我想了解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, 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); }; 

variablesapp同时在函数内被分配和使用。 这怎么能工作? 其他地方没有app定义。 在这里find真正的来源。

该函数被创build并分配给appvariables。 这是一个正常的函数expression式分配。

然后,这两个mixin()方法添加到appfunction。 所以,在调用这些函数之后,它有像app.handle()app.init()

然后,再添加两个属性app.requestapp.response

然后, app.init()

然后,稍后调用app函数(当一个http请求到达时)以及被调用的时候,调用app.handle() ,它只是调用一个属性本身的函数。 这都是合法的。 这与在更传统的对象中调用this.handle()类似。

这里有一个你觉得最困惑的部分:

 var test = function() { test.doSomething(); } test.doSomething = function() { console.log("doSomething"); } test(); // causes test.doSomething() to get called