不能理解这个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并分配给app
variables。 这是一个正常的函数expression式分配。
然后,这两个mixin()
方法添加到app
function。 所以,在调用这些函数之后,它有像app.handle()
和app.init()
。
然后,再添加两个属性app.request
和app.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