javascript 回调函数中的参数从何而来? [英] Where do the parameters in a javascript callback function come from?

查看:39
本文介绍了javascript 回调函数中的参数从何而来?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我理解回调函数的本质是函数作为参数传递给另一个函数后再次执行.但是,我对回调函数中的变量来自何处感到困惑,如下面的 node.js 示例所示:

I understand the essence of callback functions in that the function is executed again after being passed as the parameter to another function. However, I'm confused as to where the variables inside the callback function come from as shown in the following node.js example:

router.get('/', function(req, res){
    res.render('index', {});
});

变量 req 和 res 是如何填充的?一个解释我如何只调用 res.render(...) 而不声明 res 自己的例子将不胜感激.

How do the variables req and res get populated? An example explaining how I can just call res.render(...) without declaring res myself would be greatly appreciated.

推荐答案

当调用普通的非回调函数时,它们来自同一个地方,在调用时.

They come from the same place they come from when a normal non callback function is invoked, at invocation time.

如果你有这个功能,

function add (a, b) {
  return a + b
}

当你调用 add 时,你知道 a 和 b 来自,就可以了,

You're fine with knowing that a and b come from when you invoke add,

add(1,2)

回调的原理是一样的,不要因为稍后调用它而让你的大脑完全扭曲.

and it's the same principle with callbacks, don't let your brain get all twisted just because it's getting invoked later.

在某个时候你传递给 router.get 的函数将被调用,当它调用时,它会收到 reqres.

At some point the function you pass to router.get is going to be invoked, and when it does, it will receive req and res.

让我们假设 router.get 的定义是这样的

Let's pretend the definition for router.get looks like this

router.get = function(endpoint, cb){
   //do something
   var request = {}
   var response = {}
   cb(request, response) // invocation time
}

就您的示例而言,只要调用 .get,节点就可以传递您的函数请求和响应.

In the case of your example, it's just up to node to pass your function request and response whenever .get is invoked.

这篇关于javascript 回调函数中的参数从何而来?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆