在express.js中,当在自己的定义中使用变量“ app”时为什么没有错误?

时间:2018-09-14 04:46:24

标签: javascript express

在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;
}

1 个答案:

答案 0 :(得分:1)

  1. 在JavaScript中,var绑定被提升到包含该定义的本地或全局范围的顶部。因此,该变量已在创建闭包时定义。
  2. JS闭包在实例化时不捕获绑定变量的值。相反,自由变量直接绑定到词法环境,从而引用词法环境,因此匿名函数在实际调用时会看到app的值。
  3. 调用mixin时发生未定义的变量错误。