Home  >  Article  >  Web Front-end  >  ## Where Do Callback Function Parameters Come From in JavaScript?

## Where Do Callback Function Parameters Come From in JavaScript?

Susan Sarandon
Susan SarandonOriginal
2024-10-25 16:17:02124browse

## Where Do Callback Function Parameters Come From in JavaScript?

Callback Function Parameter Origin in JavaScript

Callback functions in JavaScript, as you mentioned, are executed after being passed as parameters to other functions. However, the origin of the parameters within the callback function can be confusing.

In the provided Node.js example:

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

The variables req and res are populated at the time the callback function is invoked. This concept is analogous to how parameters are passed in non-callback functions.

Consider this non-callback function:

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

In this example, we understand that a and b come from the function's invocation, such as add(1,2).

Similarly, callback functions receive their parameters when they are invoked. In the case of router.get, it passes request and response objects to the callback function at invocation time.

To illustrate, consider a hypothetical definition of router.get:

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

In the example provided, Node.js is responsible for passing request and response to the callback function whenever .get is invoked.

The above is the detailed content of ## Where Do Callback Function Parameters Come From in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn