javascript - 无法理解此 Express JS 源代码片段

标签 javascript node.js express

我试图了解 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.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

关于javascript - 无法理解此 Express JS 源代码片段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46598314/

相关文章:

javascript - 使用 Javascript 和 Underscore.js,如何比较 2 个数组并在匹配时替换属性?

javascript - jQuery 更改事件未按预期工作

node.js - 如何解决语法错误、意外标记、导出类型?

node.js - 使用 mongoose 更新深度嵌套的子文档

java - 如何在 Node js/Java 中捕获网络调用?

javascript - bcrypt.compare 无法在 nextjs 中设置响应 header

javascript - $scope.data 未定义但 $scope.data 存在于 $scope

javascript - 下划线中的去抖动函数

javascript - 在 mysql 连接查询的结果上过滤 v-for

javascript - API 路由在不应发生的情况下发生错误处理