我试图了解 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);
};
变量app
在函数内部同时被赋值和使用。这怎么行?其他任何地方都没有 app
的定义。寻找真正的出处here .
最佳答案
函数已创建并分配给 app
变量。这是一个普通的函数表达式赋值。
然后,两行 mixin()
向 app
函数添加方法。因此,在调用这些函数之后,它具有诸如 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
关于javascript - 无法理解此 Express JS 源代码片段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46598314/