在express.js中,我很难理解为什么createApplication()不会引发错误,因为它在定义相同变量“ app”的匿名函数中使用了app.handle(...)。
试图在jsFiddle中模仿它,但是出现了我所期望的“ app is undefined”错误。函数赋值表达式始于 创建Application()令我感到困扰:
function createApplication() {
//New variable 'app' to be defined
//by anonymous function
var app = function(req, res, next) {
app.handle(req, res, next); // But 'app' not fully defined yet!
};
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;
}
答案 0 :(得分:1)
var
绑定被提升到包含该定义的本地或全局范围的顶部。因此,该变量已在创建闭包时定义。app
的值。mixin
时发生未定义的变量错误。