javascript回调函数中的参数来自哪里? [英] Where do the parameters in a javascript callback function come from?

查看:160
本文介绍了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的情况下调用res.render(...)将非常感激。

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
}

你知道一个人就可以了和b来自你调用add时,

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的函数将被调用,当它被调用时,它将收到 req res

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天全站免登陆