函数的参数传递到哪里

问题描述 投票:0回答:2
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函数中的参数那么工作

javascript node.js function express callback
2个回答
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

-1
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.