【问题标题】:Where do the arguments of a function get passed in函数的参数在哪里传入
【发布时间】:2019-05-01 04:23:41
【问题描述】:
app.use(function(req, res, next) {
   console.log(req)
});

当函数被调用时,该函数的实际参数在哪里传入,以及为函数提供参数的原因是什么。

意思是我对函数的理解是,首先你要有函数定义

function timesTwo(x){
   return 2*x
}

其中 x 是一个参数。这段代码本身不会执行任何函数,因为它没有被调用并提供参数

timesTwo(3) //will return 6

仅因为我调用了函数并传递了 3 的参数才有效

为什么会这样

function(req, res, next) {
   console.log(req)
});

如果我没有像 timesTwo 函数那样调用/提供参数就可以工作

【问题讨论】:

  • 你将一个函数传递给app.use,它会从那里被调用,在Javascript中你可以传递函数和变量。
  • 这称为callback函数。你不叫它。您将它传递给另一个执行某些操作的函数,当结果准备好时,它会使用参数调用您的 callback 函数。
  • 但是在我的例子中,req,res 的来源不仅仅是像 'x' 这样的占位符参数。
  • app.use 提供 req、res 和 next。
  • 它们来自应用程序调用您的函数时。

标签: javascript node.js function express callback


【解决方案1】:

您正在传递一个稍后会调用的回调函数。

这是一个例子:

const app = {
  list:[],
  use(fn) {
    // save  the reference to the function so it can be called later
    this.list.push(fn);
  },
  handle() {
    // The callback function is called here. Notice that I don't know what
    // the function was called, and it doesn't matter if it was a named
    // or anonymous function. I just call it with whatever arguments
    // I want.
    const time = new Date().toISOString();
    this.list.forEach( fn => fn( time ) );
  }
}

setInterval(app.handle.bind(app), 2000);

function myFunction (time) {
  console.log('MYFUNC', time)
};

app.use(myFunction); // Adds a named function
app.use( function(time) { console.log("Anonymous", time) } ); // adds an anonymous function

【讨论】:

    【解决方案2】:

    这不是用户定义的函数,实际上是 express 框架中的中间件(也可以说是回调函数)。参数已经由 express 框架设置/管理。当您将请求发送到服务器时,它将自动执行。

    【讨论】:

    • This is not a user-defined function这是一个用户定义的函数
    猜你喜欢
    • 2011-05-10
    • 2014-02-08
    • 2023-04-02
    • 2012-04-24
    • 1970-01-01
    • 2012-08-30
    • 1970-01-01
    • 2020-03-27
    • 2015-02-21
    相关资源
    最近更新 更多